Search code examples
rdifftime

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


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


Solution

  • 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