Convert UNIX epoch to Date object

Andreas picture Andreas · Nov 19, 2012 · Viewed 113.6k times · Source

I'm plotting and performing calculations on uniformly distributed time series. The timestamps are currently stored as integers representing the number of seconds since the UNIX epoch (e.g. 1352068320), but Date objects seem more appropriate for plotting. How can I do the conversion?

I've read ?Date, ?as.Date and ??epoch, but seem to have missed that information.

Answer

Dirk Eddelbuettel picture Dirk Eddelbuettel · Nov 19, 2012

Go via POSIXct and you want to set a TZ there -- here you see my (Chicago) default:

R> val <- 1352068320
R> as.POSIXct(val, origin="1970-01-01")
[1] "2012-11-04 22:32:00 CST"
R> as.Date(as.POSIXct(val, origin="1970-01-01"))
[1] "2012-11-05" 
R> 

Edit: A few years later, we can now use the anytime package:

R> library(anytime)
R> anytime(1352068320)
[1] "2012-11-04 16:32:00 CST"
R> anydate(1352068320)
[1] "2012-11-04"
R> 

Note how all this works without any format or origin arguments.