Converting timestamp in microseconds to data and time in r

冷暖自知 提交于 2019-12-04 05:33:51

问题


I'm trying to convert a timestamp in microseconds to the following format in R:

YYYY-MM-DD HH:MM:SS

I've tried different approaches, but couldn't succeed. Following my code:

options(digits=16) value = 1521222492687300 as.POSIXct(value, tz = "UTC", origin="1970-01-01 00:00:00")

And I get this as return:

[1] "48207591-10-13 12:15:00 UTC"

Even divided by 1000, as some posts suggested, I'm still getting a non sense result:

as.POSIXct(value/1000, tz = "UTC", origin="1970-01-01 00:00:00") [1] "50175-08-15 19:31:27.300048 UTC"

Any suggestion to solve this problem?


回答1:


As Gabor hinted you need to divide by 1e6, not 1e3:

R> v <- 1521222492687300
R> v
[1] 1.52122e+15
R> anytime::anytime(v / 1e6)
[1] "2018-03-16 12:48:12.6872 CDT"
R> 

Same of course with as.POSIXct etc but you nee to supply the redundant origin:

R> as.POSIXct(v / 1e6, origin="1970-01-01")
[1] "2018-03-16 12:48:12.6872 CDT"
R> 

One way to see your scale is to convert current time:

R> w <- as.numeric(Sys.time())
R> c(v, w)
[1] 1.52122e+15 1.52346e+09
R> 

which makes the scaling difference more obvious.



来源:https://stackoverflow.com/questions/49776854/converting-timestamp-in-microseconds-to-data-and-time-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!