Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

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

like image 913
nikUoM Avatar asked Jul 09 '18 00:07

nikUoM


2 Answers

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
like image 169
Ozan Avatar answered Sep 28 '22 09:09

Ozan


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)
like image 20
rgt47 Avatar answered Sep 28 '22 08:09

rgt47