R lubridate converting seconds to date

broccoli picture broccoli · Dec 21, 2012 · Viewed 16.7k times · Source

I have a simple question regarding R's lubridate package. I've a series of timestamps in seconds since epoch. I want to convert this to YYYY-MM-DD-HH format. In base R, I can do something like this to first convert it to a date format

> x = as.POSIXct(1356129107,origin = "1970-01-01",tz = "GMT")
> x
[1] "2012-12-21 22:31:47 GMT"

Note the above just converts it to a date format, not the YYYY-MM-DD-HH format. How would I do this in lubridate? How would I do it using base R?

Thanks much in advance

Answer

leerssej picture leerssej · Oct 13, 2017

lubridate has an as_datetime() that happens to have UNIX epoch time as the default origin time to make this really simple:

> as_datetime(1356129107)
[1] "2012-12-21 22:31:47 UTC"

more details can be found here: https://rdrr.io/cran/lubridate/man/as_date.html