27
votes

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

3
You're confused. POSIXct is not a Date format, it is a Datetime format. There is storage and there is display formatting. Don't confuse them.Dirk Eddelbuettel

3 Answers

34
votes

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

14
votes

Dirk is correct. However, if you are intent on using lubridate functions:

paste( year(dt), month(dt), mday(dt), hour(dt) sep="-")

If on the other hand you want to handle the POSIXct objects the way they were supposed to be used then this should satisfy:

format(x, format="%Y-%m-%d-%H")
1
votes

I use the lubridate solution provided by @leerssej

But in case anyone prefers @IRTFM's solution in base R, but also wants minutes and seconds, here's an example of how to do that:

as.POSIXct("2019-03-15 16:17:42" , format="%Y-%m-%d %H:%M:%OS")