问题
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.
回答1:
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.
回答2:
In lubridate library date and time saved as the number of seconds since 1970-01-01 00:00:00 UTC. So you can do
library(lubridate)
as_datetime(1352068320)
[1] "2012-11-04 22:32:00 UTC"
来源:https://stackoverflow.com/questions/13456241/convert-unix-epoch-to-date-object