将Epoch秒数转换为本地时间

假设我在Unix Epoch(1970-01-01 00:00:00Z)中给出了几个时间戳(整数)(秒)。

我如何将它们转换为当地时区的适当日期时间? 我一直在寻找as.POSIXct帮助页面以及SO上的相关问题。 UTC很容易做到,但出于某种原因,我似乎无法直接为当地时区或另一个时区(顺便说一下,我恰好在“America / Los_Angeles”或“PST5PDT”中根据白天储蓄是否在指定时间生效,变成“PST或”PDT“;所以我通常指定基于位置的时区而不是”PST“或”PDT“,这些都是非常挑剔的)。

设置示例:

z <- c(1360527317,1363019665)

在perl中快速验证:

echo -n 1360527317,1363019665 | perl -ne '
use POSIX /strftime/;
$fmt = "%Y-%m-%d %H:%M:%S";
for (split /,/) {
  $loc=strftime("$fmt %Z", localtime($_));
  $gmt=strftime("$fmt GMT", gmtime($_));
  print "$_: $loc $gmtn";
}'
# gives:
1360527317: 2013-02-10 12:15:17 PST 2013-02-10 20:15:17 GMT
1363019665: 2013-03-11 09:34:25 PDT 2013-03-11 16:34:25 GMT

首先,显而易见(以UTC表示):

as.POSIXct(z, origin='1970-01-01', tz='GMT')
# --> [1] "2013-02-10 20:15:17 GMT" "2013-03-11 16:34:25 GMT"

以下是我尝试过的不起作用的东西:

as.POSIXct(z, origin='1970-01-01')
# --> (wrong) [1] "2013-02-10 20:15:17 PST" "2013-03-11 17:34:25 PDT"

as.POSIXct(z, origin='1970-01-01 00:00:00 Z')
# --> (wrong) [1] "2013-02-10 20:15:17 PST" "2013-03-11 17:34:25 PDT"

as.POSIXct(z, origin='1970-01-01', tz='America/Los_Angeles')
# --> (wrong) [1] "2013-02-10 20:15:17 PST" "2013-03-11 17:34:25 PDT"

在我的智慧的结尾,这是给了我正确结果的东西:

now=Sys.time(); now+(z-unclass(now))
# --> [1] "2013-02-10 12:15:17 PST" "2013-03-11 09:34:25 PDT"

顺便说一句,在我的系统上:

now=Sys.time()
now
# --> [1] "2013-03-13 18:26:05 PDT"
unclass(now)
# --> [1] 1363224365

所以看起来我的设置和本地时区是正确的。

任何想法我做错了上面没有工作的线?

同时,我将使用以下技巧,希望对其他人有用:

localtime <- function(t) {
  now = Sys.time();
  return(now+(unclass(t)-unclass(now)))
}
# quick test:
localtime(Sys.time())
# --> [1] "2013-03-13 18:33:40 PDT"
localtime(z)
# --> [1] "2013-02-10 12:15:17 PST" "2013-03-11 09:34:25 PDT"

尝试将Date传递给origin而不是字符串

as.POSIXct(z, origin=as.Date('1970-01-01'), tz='America/Los_Angeles')

您需要区分解析/存储为UTC

R> pt <- as.POSIXct(z, origin=as.Date("1970-01-01"))
R> pt
[1] "2013-02-10 14:15:17 CST" "2013-03-11 11:34:25 CDT"

现在你可以在任何你想要的TZ中显示:

R> format(pt, tz="America/Chicago")
[1] "2013-02-10 14:15:17" "2013-03-11 11:34:25"
R> format(pt, tz="America/Los_Angeles")
[1] "2013-02-10 12:15:17" "2013-03-11 09:34:25"
R> 
链接地址: http://www.djcxy.com/p/18493.html

上一篇: converting seconds from the Epoch into localtime

下一篇: Convert python datetime to epoch with strftime