How to format a difftime object to a string with HH:MM:SS

nik*_*UoM 4 r difftime

I think this is quite a simple question, I am however incapable of solving it, so any help would be greatly appreciated.

I have a difftime object, generated as follows:

> duration <- difftime(end_time, start_time)
> duration
Time difference of 15.74106 secs
Run Code Online (Sandbox Code Playgroud)

The end_time and start_time objects are POSIXct objects and look like this:

> c(start_time, end_time)
[1] "2018-07-08 20:07:56 EDT" "2018-07-08 20:08:12 EDT"
Run Code Online (Sandbox Code Playgroud)

I need duration to be displayed in HH:MM:SS format - i.e. like this, in a string:

"00:00:15"
Run Code Online (Sandbox Code Playgroud)

Is there a simple answer to this question? I've played around with the format argument, but it's not working. Thanks in advance for your help, Nik

Oza*_*147 6

One possible solution is:

library(hms)

duration <- difftime("2018-07-08 20:08:12 EDT", "2018-07-08 20:07:56 EDT")
as.hms(duration)
# 00:00:16
Run Code Online (Sandbox Code Playgroud)


小智 5

使用基本 R 的通用解决方案,灵感来自 G. Grothendieck 对问题的回答: Outputting difftime as HH:MM:SS:mm in R

duration <- difftime(end_time, start_time, units="secs")
x <- abs(as.numeric(duration))
sprintf("%02d:%02d:%02d:%02d", x %/% 86400,  x %% 86400 %/% 3600, x %% 3600 %/% 
60,  x %% 60 %/% 1)
Run Code Online (Sandbox Code Playgroud)