在lubridate中的一个简单问题 - 我想将一个hms对象转换为自当日起适当的秒数。
例如:
library(lubridate)
hms("12:34:45")
我想知道12小时34分钟45秒究竟是多少秒
类似于明显的方法
seconds(hms("12:34:45"))
仅返回
45s
这不是我想要的。如何将这些hms值转换为秒?我想使用lubridate
R>lubridate::period_to_seconds(hms("01:00:00"))
从 00:00:00 开始数,预期为 3600 秒的数字计数,或者在上述情况下:
R>period_to_seconds(hms("12:34:45"))
无论使用哪个包,都需要将日期/时间对象转换为自纪元以来的 POSIXct 表示,因此最好在基础 R 中完成此操作,因此可以使用ISOdatetime()
函数并指定任意日期,使用当天即可:
R> difftime(ISOdatetime(2012,7,2,12,34,45), ISOdatetime(2012,7,2,0,0,0))
Time difference of 12.5792 hours
所以我们想要秒:
R> difftime(ISOdatetime(2012,7,2,12,34,45), ISOdatetime(2012,7,2,0,0,0),
+ unit="secs")
Time difference of 45285 secs
我们可以将其转换为数字:
R> as.numeric(difftime(ISOdatetime(2012,7,2,12,34,45), +
ISOdatetime(2012,7,2,0,0,0), unit="secs"))
[1] 45285
编辑:回到“lubridate”问题,这可能是一个错误:
> 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>
as.duration
更准确,后者(我认为)只是将每个部分转换为“默认”秒数。在 lubridate 中,您首先必须将其转换为时间间隔,这基本上就是您在这里所做的,我想。 - joranout <- as.POSIXct("12:34:45", format="%H:%M:%S",tz="UTC"); difftime(out,trunc(out,"day"),units="secs")
- thelatemailas.numeric(as.POSIXct(paste("1970-01-01", "12:34:45")))
- user3226167
as.duration()
可能是吗? - joran