views:

198

answers:

1

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

+2  A: 

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.

Dirk Eddelbuettel
Dirk - Thanks for your explanation. So what do you suggest that I do here? I have an entire time series dataset with unix timestamps. I was hoping to use xts to represent them.
signalseeker
Well I do this all the time too (when interfacing data from internal data warehouses) and I just accept that `as.POSIXct(vecOfTimestamps)` will get local time values. Looking at what we found here, going via `as.POSIXlt` as an extra step first may help. I still have writing of a proper C++ representation as a TODO item for Rcpp as well.
Dirk Eddelbuettel
Thanks for now I will take your suggestion for going the extra step. Something to look into more deeply when I get a chance. Is there an R bug tracker where I can post this?
signalseeker
Start with the r-devel archives (maybe via rseek.org and the list tab). There may be a solution that I have forgotten about.
Dirk Eddelbuettel