2

How do I convert my results (time differences) in the following three format (preferably using lubridate)

  1. HH:MM
  2. HH:MM:SS
  3. 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
SiH
  • 1,378
  • 4
  • 18

1 Answers1

2

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 seconds, 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"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks @akrun. Is it also possible to round off `periods` to nearest minute. For ex - `seconds_to_period(difftime(time_3, time_2, units = 'sec'))` results into "2H 13M" and not give "2H 13M 9S" – SiH Sep 05 '21 at 20:13
  • @SiD You can use the function `format` to specify the format i.e. if you want only "HH:MM", it is the default option `f1(time_2, time_3)` – akrun Sep 05 '21 at 20:17
  • Thanks, this problem is solved. I have another simple question, I have asked it separately - https://stackoverflow.com/questions/69066968/round-off-periods-to-nearest-minutes-using-lubridate – SiH Sep 05 '21 at 20:28