将unix秒以毫秒为单位转换为POSIXct / POSIXlt

时间:2010-03-16 18:40:15

标签: datetime r

为什么在R?

中将unix时间戳转换为datetime对象时会有所不同?
> as.POSIXlt(1268736919, origin="1970-01-01", tz="America/New_York")
[1] "2010-03-16 06:55:19 EDT"

> as.POSIXct(1268736919, origin="1970-01-01", tz="America/New_York")
[1] "2010-03-16 11:55:19 EDT"

POSIXlt的结果实际上是正确的。

另外,有没有办法在不指定原点的情况下进行此转换?

由于

1 个答案:

答案 0 :(得分:20)

帮助页面实际上暗示了差异:

Value:

     ‘as.POSIXct’ and ‘as.POSIXlt’ return an object of the appropriate
     class.  If ‘tz’ was specified, ‘as.POSIXlt’ will give an
     appropriate ‘"tzone"’ attribute.

这个东西很挑剔 - 我认为as.POSIXct发生了隐含的TZ转换。考虑一下

R> print(as.numeric(as.POSIXct(as.POSIXlt(1268736919, 
                               origin="1970-01-01"))), digits=10)
[1] 1268736919
R> print(as.numeric(as.POSIXct(1268736919, origin="1970-01-01")), digits=10)
[1] 1268758519

第二个(使用as.POSIXct)不返回原始输入。不幸的是,Brian D. Ripley似乎是唯一拥有此处所有细节的人。

最后,如果没有原点,你就无法做到。但是你可以定义使用epoch作为原点的包装器(如此处)或使用2000-01-01或者......保持一致。