简体   繁体   English

R lubridate 将秒转换为日期

[英]R lubridate converting seconds to date

I have a simple question regarding R's lubridate package.我有一个关于 R 的 lubridate 包的简单问题。 I've a series of timestamps in seconds since epoch.自纪元以来,我有一系列以秒为单位的时间戳。 I want to convert this to YYYY-MM-DD-HH format.我想将其转换为 YYYY-MM-DD-HH 格式。 In base R, I can do something like this to first convert it to a date format在基础 R 中,我可以先将其转换为日期格式

> 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.请注意,以上只是将其转换为日期格式,而不是 YYYY-MM-DD-HH 格式。 How would I do this in lubridate?我将如何在 lubridate 中做到这一点? How would I do it using base R?我将如何使用基础 R 做到这一点?

Thanks much in advance非常感谢提前

lubridate has an as_datetime() that happens to have UNIX epoch time as the default origin time to make this really simple: lubridate有一个as_datetime()恰好有 UNIX 纪元时间作为默认的原始时间,使这变得非常简单:

> 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 : //rdrr.io/cran/lubridate/man/as_date.html

Dirk is correct.德克是对的。 However, if you are intent on using lubridate functions:但是,如果您打算使用 lubridate 函数:

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:另一方面,如果您想以它们应该使用的方式处理POSIXct对象,那么这应该满足:

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

I use the lubridate solution provided by @leerssej我使用@leerssej 提供的 lubridate 解决方案

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:但是,如果有人更喜欢 @IRTFM 在基础 R 中的解决方案,但也想要 minutes 和 seconds ,这里有一个如何做到这一点的例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM