简体   繁体   English

在R中,使用lubridate将hms对象转换为秒

[英]In R, use lubridate to convert hms objects into seconds

simple question in lubridate--I want to convert an hms object into its appropriate number of seconds since the start of the day. lubridate中的一个简单问题-我想将hms对象转换为自一天开始以来的适当秒数。

For instance 例如

library(lubridate)
hms("12:34:45")

then I want to know exactly how long 12 hours, 34 minutes, and 45 seconds is, in seconds 那么我想确切地知道12小时34分45秒以秒为单位

something obvious like 类似的东西

seconds(hms("12:34:45"))

just returns 刚回来

45s

which is not what I want. 这不是我想要的。 How do I convert these hms values into seconds? 如何将这些hms值转换为秒? I'd like to use lubridate 我想使用lubridate

R>lubridate::period_to_seconds(hms("01:00:00")) 

从00:00:00或在上述情况下,给出预期的3600秒作为数字计数:

R>period_to_seconds(hms("12:34:45")) 

It doesn't matter which package you use -- it will have convert a date / datetime object into a POSIXct representation of seconds since the epoch. 不管使用哪个包,它都会将日期/日期时间对象转换为自纪元以来的秒的POSIXct表示形式。 So you may as well do it in base R -- so here deploy ISOdatetime() with an arbitrary day, using today: 因此,您也可以在基数R中进行操作-因此,请在今天使用任意天部署ISOdatetime()

R> difftime(ISOdatetime(2012,7,2,12,34,45), ISOdatetime(2012,7,2,0,0,0))
Time difference of 12.5792 hours

So we want seconds: 所以我们要秒:

R> difftime(ISOdatetime(2012,7,2,12,34,45), ISOdatetime(2012,7,2,0,0,0), 
+          unit="secs")
Time difference of 45285 secs

And we can cast to numbers: 我们可以转换为数字:

R> as.numeric(difftime(ISOdatetime(2012,7,2,12,34,45), +
                       ISOdatetime(2012,7,2,0,0,0), unit="secs"))
[1] 45285

Edit: And getting back to lubridate, this is arguably a bug: 编辑:回到润滑,这可以说是一个错误:

> hms("12:34:45") - hms("00:00:00")
[1] 12 hours, 34 minutes and 45 seconds
R> as.numeric(hms("12:34:45") - hms("00:00:00"))
[1] 45
R>

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

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