How do I convert my results (time differences) in the following three format (preferably using lubridate
)
HH:MM
HH:MM:SS
MM:SS
library(lubridate)
time_1 <- ymd_hms("2021-01-01 12:00:00")
time_2 <- ymd_hms("2021-01-01 12:12:36")
time_3 <- ymd_hms("2021-01-01 14:25:45")
time_diff_32 <- time_3 - time_2
time_diff_31 <- time_3 - time_1
time_diff_21 <- time_2 - time_1
Instead of directly doing the -
, use difftime
with units
which will have more control on the output units i.e. if we convert it to sec
onds, then we can use the seconds_to_period
from lubridate
and then extract the various components to create the format
as in expected output
library(lubridate)
out <- seconds_to_period(difftime(time_3, time_2, units = 'sec'))
sprintf('%02d:%02d', out@hour, second(out))
sprintf('%02d:%02d:%02d', out@hour, out@minute, second(out))
sprintf('%02d:%02d', out@minute, second(out))
If there are more than one object, we can create a function for reuse
f1 <- function(time1, time2, format = "HH:MM") {
tmp <- lubridate::seconds_to_period(difftime(time2, time1, units = 'sec'))
switch(format,
"HH:MM" = sprintf('%02d:%02d', tmp@hour, second(tmp)),
"HH:MM:SS" = sprintf('%02d:%02d:%02d', tmp@hour,
tmp@minute, second(tmp)),
"MM:SS" = sprintf('%02d:%02d', tmp@minute,
second(tmp)))
}
-testing
> f1(time_2, time_3)
[1] "02:09"
> f1(time_2, time_3, format = "HH:MM:SS")
[1] "02:13:09"
> f1(time_2, time_3, format = "MM:SS")
[1] "13:09"