How to control the unit of a time difference in R?

I calculate some durations in R as shown below. Depending of the value of the duration, the unit can be minutes, hours, days, etc.:

library(lubridate)
start <- "2022-08-27 10:06:58"
end <- "2022-08-27 10:10:24"
start <- as_datetime(start)
end   <- as_datetime(end)
end - start
# Time difference of 3.433333 mins
start - Sys.time()
# Time difference of -3.136468 days

I want to always get the durations in minutes, how could I achieve that?

>Solution :

You do not need lubridate but you likely want an argument to difftime():

Code

start <- as.POSIXct("2022-08-27 10:06:58")
end <- as.POSIXct("2022-08-27 10:10:24")
difftime(end, start, unit="mins")

Output

> start <- as.POSIXct("2022-08-27 10:06:58")
> end <- as.POSIXct("2022-08-27 10:10:24")
> difftime(end, start, unit="mins")
Time difference of 3.43333 mins
> 

And yup, likely a duplicate a few times over.

Leave a Reply