Find time difference in both hours and minutes in R

Here is one way to do this in base R :

get_in_hm <- function(time1, time2) {
  format(as.POSIXct(as.numeric(difftime(time1, time2, units = 'secs')), 
         origin = '1970-01-01', tz = 'UTC'), '%H:%M')  
}

get_in_hm("2020-09-14 18:01:31", "2020-09-14 17:47:38")
#[1] "00:13"

Get the difftime output in seconds, convert to numeric, consider this as seconds since epoch and return the hour and minute from the captured datetime.


If you want to round the difference you can use :

get_in_hm <- function(time1, time2) {
  format(as.POSIXct(round(as.numeric(difftime(time1,time2,units = 'mins'))) * 60,
          origin = '1970-01-01', tz = 'UTC'), '%H:%M')  
}

get_in_hm("2020-09-14 18:01:31", "2020-09-14 17:47:38")
#[1] "00:14"

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top