9

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

3 Answers 3

8

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
1
  • 1
    hi @Ozan147 - thanks for this answer. this works great!!
    – nikUoM
    Jul 9, 2018 at 0:49
5

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)
2

This link maybe helpful. It explains little or more of what you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.