1

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?

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225

1 Answers1

2

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.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • [This one](https://stackoverflow.com/questions/32312925/time-difference-in-years-with-lubridate) is easy to adapt to minutes. – Rui Barradas Aug 30 '22 at 13:35
  • 1
    It's all just plain subtraction and scaling so I never used anything but base R for this. One _can_ use `lubridate` and many users find it appealing, but as I said one does not _need_ it as the basic operations are all available in base R. – Dirk Eddelbuettel Aug 30 '22 at 13:37
  • No, it wasn't me. And I didn't close because it is not an exact duplicate and you'll never know what "easy" to adapt means to others. – Rui Barradas Aug 30 '22 at 14:37
  • Oh but additional context is that Stephane and I "know" each other I know how lingual and knowledgeable he is. – Dirk Eddelbuettel Aug 30 '22 at 14:52