Home > front end >  Difference between dates with HH:MM:SS format
Difference between dates with HH:MM:SS format

Time:05-11

I have a DF and I want to make the difference between dates (date and time) with HH:MM:SS result. See my example:

DATE_1 <- c('06-05-2022 11:06:48','04-05-2022 06:11:55','17-02-2022 21:06:50')
DATE_2 <- c('06-05-2022 12:15:00','04-05-2022 06:35:00','18-02-2022 21:21:00')
DF <- data.frame(DATE_1 = lubridate::dmy_hms(DATE_1), DATE_2 = lubridate::dmy_hms(DATE_2))

My intended result is:

DF <- DF %>% 
  mutate(DIF = c('01:08:12','00:23:05','24:14:10'))

I don't want my result to come in the format like this: 1H 31M 10S or 150d 21H 14M 10S.

CodePudding user response:

Another solution with hms::as_hms:

DF %>% mutate(DIF = hms::as_hms(difftime(DATE_2,DATE_1)))

               DATE_1              DATE_2      DIF
1 2022-05-06 11:06:48 2022-05-06 12:15:00 01:08:12
2 2022-05-04 06:11:55 2022-05-04 06:35:00 00:23:05
3 2022-02-17 21:06:50 2022-02-18 21:21:00 24:14:10

CodePudding user response:

The best way I know of is first creating a lubridate::period object and then manually constructing the HH:MM:SS form you want from that object:

dplyr::mutate(DF,
              DIF_period = lubridate::seconds_to_period(difftime(DATE_2, DATE_1, units = "secs")),
              DIF = paste(sprintf("d", DIF_period@day*24 DIF_period@hour),
                          sprintf("d", DIF_period@minute),
                          sprintf("d", [email protected]), sep = ":"))

which gives

               DATE_1              DATE_2    DIF_period      DIF
1 2022-05-06 11:06:48 2022-05-06 12:15:00     1H 8M 12S 01:08:12
2 2022-05-04 06:11:55 2022-05-04 06:35:00        23M 5S 00:23:05
3 2022-02-17 21:06:50 2022-02-18 21:21:00 1d 0H 14M 10S 24:14:10

CodePudding user response:

Here a moduloish solution.

f <- \(...) {
  d <- as.numeric(difftime(..., units='mins'))
  sprintf('d:d:d', d %/% 60, floor(d %% 60), round(((d %% 60) %% 1)*60))
}
do.call(f, unname(rev(DF)))
# [1] "01:08:12" "00:23:05" "24:14:10"

Data:

DF <- structure(list(DATE_1 = structure(c(1651835208, 1651644715, 1645132010
), class = c("POSIXct", "POSIXt"), tzone = "UTC"), DATE_2 = structure(c(1651839300, 
1651646100, 1645219260), class = c("POSIXct", "POSIXt"), tzone = "UTC")), class = "data.frame", row.names = c(NA, 
-3L))
  •  Tags:  
  • r
  • Related