Search code examples
rlubridate

How can we add time durations HMS formats in lubridate


Though there are a few questions and a few workaround answers too, but I cannot find direct methods to add hours/minutes/seconds objects?

Let's consider through an example. I have a vector a having time time intervals in HH:MM:SS format. I can parse it easily using lubridate::hms as shown below

a <- c("38:03:24", "6:50:58", "0:31:54", "8:13:51")
hms(a)

[1] "38H 3M 24S" "6H 50M 58S" "31M 54S"    "8H 13M 51S"

But how can I sum this vector?

> sum(hms(a))
[1] 187

as.period, seconds etc. cannot help. So How can I add up all the values in the given vector without converting it to first seconds then modulo division then minutes then modulo division....

my expected output would be like 54H 8M 7S

I have another issue, when I add each element separately, it does so in the required format, but not correctly? why? and How to correct it?

> hms(a)[1] + hms(a)[2]
[1] "44H 53M 82S"

clearly 82S should be converted to 22S and 53M to 54M


Solution

  • a <- c("38:03:24", "6:50:58", "0:31:54", "8:13:51")
    
    td <- as.period(seconds(sum(as.numeric(hms(a)))), unit = "hour")
    # [1] "53H 40M 7S"
    sprintf('%02d:%02d:%02d', td$hour, td$minute, td$second)
    # [1] "53:40:07"