1

假设我有几个从 Unix 纪元 (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 $gmt\n";
}'
# 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"
4

2 回答 2

1

您需要区分解析/存储为 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> 
于 2013-03-14T01:47:17.127 回答
1

尝试传递一个Datetoorigin而不是一个字符串

as.POSIXct(z, origin=as.Date('1970-01-01'), tz='America/Los_Angeles')
于 2013-03-14T01:38:34.633 回答