30

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

broccoli
  • 4,738
  • 10
  • 42
  • 54
  • 5
    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 Dec 21 '12 at 22:54

3 Answers3

38

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

leerssej
  • 14,260
  • 6
  • 48
  • 57
14

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")
IRTFM
  • 258,963
  • 21
  • 364
  • 487
1

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")
stevec
  • 41,291
  • 27
  • 223
  • 311