Is it possible to print a duration with HH:MM:SS format?

让人想犯罪 __ 提交于 2020-12-31 06:20:48

问题


t1<-as.POSIXct("2017-03-02 11:58:20")
t2<-as.POSIXct("2017-03-02 12:00:05")
print(lubridate::as.duration(lubridate::interval(t1,t2)))

[1] "105s (~1.75 minutes)"

Is it possible to have the duration expressed in HH:MM:SS? So in this case it would be:

00:01:45


回答1:


You can use seconds_to_period from lubridate with sprintf

library(lubridate)
td <- seconds_to_period(difftime(t2, t1, units = "secs"))
sprintf('%02d:%02d:%02d', td@hour, minute(td), second(td))
#[1] "00:01:45"

This is based on an earlier discussion - Converting seconds to days: hours:minutes:seconds in r?




回答2:


To stay in the lubridate mindset:

t1<-as.POSIXct("2017-03-02 11:58:20")
t2<-as.POSIXct("2017-03-02 12:00:05")
dur <- lubridate::as.period(lubridate::as.duration(lubridate::interval(t1,t2)))
sprintf('%02d %02d:%02d:%02d', day(dur), hour(dur), minute(dur), second(dur))

Normally, the period class might be inaccurate (leap days etc) but since it was first passed through duration, it should be right.



来源:https://stackoverflow.com/questions/42557205/is-it-possible-to-print-a-duration-with-hhmmss-format

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