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 calculate time difference between two H:M:S character strings in R?

I have two character strings that describe time of day.

session_start <- "9:31:56"
session_end <- "10:57:25"

I essentially want to subtract session_start from session_end to get the time difference (or time elapsed to put it another way). How can I do that?

I’d finally like to convert the result of session_end - session_start from an H:M:S output to only total minutes. Thanks

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 :

a <- diff(as.POSIXct(paste(Sys.Date(), c(session_start, session_end))))
as.numeric(a, units = 'mins')

[1] 85.48333

using data.table:

(b <- diff(data.table::as.ITime(c(session_start,session_end))))
[1] "01:25:29"

To convert this to minutes use:

as.numeric(structure(b, class='difftime', units='secs'), units='mins')
[1] 85.48333

Using basic math:

d <- read.table(text=c(session_start,session_end), sep = ':')
diff(c(c(60, 1, 1/60) %*% t(d)))
[1] 85.48333
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