简体   繁体   中英

How to convert a UNIX time in milliseconds to POSIXlt in R?

I'm trying to parse the value

1454181695067-0800

As a datetime object in R. This value is milliseconds since epoch.

If I truncate the timezone and the milliseconds part of the value I can parse, ie

> as.POSIXlt(1454181695, origin = "1970-01-01")
[1] "2016-01-30 11:21:35 PST"

However, is it possible to do it all in one function call, which includes the milliseconds and handles the -0800 portion correctly?

I'd prefer to do it with the default R functionality.

With your timestamp as a character:

x="1454181695067-0800"

Then split it with read.fwf and construct:

> bits = read.fwf(textConnection(x),widths=c(10,3,1,2,2))
> as.POSIXlt(bits$V1+bits$V2/1000, origin="1970-01-01") + ifelse(bits$V3=="-",-1,1)* (bits$V4*60*60+bits$V5*60)
[1] "2016-01-30 11:21:35 GMT"

Although the milliseconds don't show, they are there. If you call that thing t0 then:

> as.numeric(t0 - as.integer(t0))
[1] 0.06699991

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM