SiH
SiH

Reputation: 1546

Round off periods to nearest minutes using lubridate

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'))

Upvotes: 1

Views: 207

Answers (2)

zx8754
zx8754

Reputation: 56159

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"

Upvotes: 3

akrun
akrun

Reputation: 887128

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"

Upvotes: 1

Related Questions