R lubridate converting seconds to date

我只是一个虾纸丫 提交于 2019-12-21 03:36:31

问题


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


回答1:


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")



回答2:


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



来源:https://stackoverflow.com/questions/13998206/r-lubridate-converting-seconds-to-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!