Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading