Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting unix seconds in milliseconds to POSIXct/POSIXlt

Tags:

datetime

r

Why do I see a difference when I convert a unix timestamp to datetime object in R?

> 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"

The result from POSIXlt is actually correct.

Also, is there a way to do this conversion without specifying the origin?

Thanks

like image 311
signalseeker Avatar asked Mar 16 '10 18:03

signalseeker


People also ask

How do you convert milliseconds to seconds in Unix?

One millisecond = 1/1000 in UNIX time. One second = 1 in UNIX time.

What is the difference between POSIXct and POSIXlt?

There are two POSIX date/time classes, which differ in the way that the values are stored internally. The POSIXct class stores date/time values as the number of seconds since January 1, 1970, while the POSIXlt class stores them as a list with elements for second, minute, hour, day, month, and year, among others.

Does Unix timestamp have milliseconds?

This returns the number of milliseconds since the Unix Epoch of the Day.

What is POSIXct format?

POSIXct stores date and time in seconds with the number of seconds beginning at 1 January 1970. Negative numbers are used to store dates prior to 1970. Thus, the POSIXct format stores each date and time a single value in units of seconds. Storing the data this way, optimizes use in data.


1 Answers

The help page actually hints at a difference:

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.

This stuff is finicky -- I think there is an implicit TZ conversion happening for as.POSIXct. Consider that

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

the second one (using as.POSIXct) does not return the original input. Unfortunately, Brian D. Ripley seems to be the only human having all the details here.

Lastly, you can't do it without the origin. But you could define wrappers that use the epoch as origin (as here) or use 2000-01-01 or ... Just keep it consistent.

like image 133
Dirk Eddelbuettel Avatar answered Oct 28 '22 06:10

Dirk Eddelbuettel