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
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"
I need duration
to be displayed in HH:MM:SS format - i.e. like this, in a string:
"00:00:15"
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
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
A general solution, using base R, inspired by G. Grothendieck's answer to the question: 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With