1

I was wondering if we can round off period to nearest minutes using lubridate. For ex - the value of time_diff is "2H 13M 9S". How can I get round off time_diff to nearest minute to get "2H 13M" (remove seconds)

library(lubridate)

time_1 <- ymd_hms("2021-01-01 12:12:36")
time_2 <- ymd_hms("2021-01-01 14:25:45")

time_diff <- seconds_to_period(difftime(time_2, time_1, units = 'sec'))
SiH
  • 1,378
  • 4
  • 18

2 Answers2

3

Convert to integer, remove seconds, then convert to period:

x <- as.integer(difftime(time_2, time_1, units = "sec"))
seconds_to_period(x - (x %% 60))
# [1] "2H 13M 0S"
zx8754
  • 52,746
  • 12
  • 114
  • 209
2

We can convert to POSIXct and then use round_date

library(lubridate)
time_diff1 <- sprintf('%02d:%02d:%02d', time_diff@hour,
     time_diff@minute, second(time_diff))
 format(round_date(as.POSIXct(time_diff1, format = '%H:%M:%S'),
       unit = "minute"), '%H:%M')
[1] "02:13"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks, is it possible to obtain in this format - "2H 13M", but not as character, I would like to further add/subtract it – SiH Sep 06 '21 at 13:38