Reputation: 8404
Is it possible to find the time difference between datetimes in both hours and mins in R? For example in
difftime("2020-09-14 18:01:31 ", "2020-09-14 17:47:38", units = "hours")
should give 00:14
in a format like (hh:mm)
Upvotes: 1
Views: 1560
Reputation: 1700
This solution will not exactly give you what you need, but is simple enough.
library(lubridate)
d <- difftime("2020-09-14 18:01:31 ", "2020-09-14 17:47:38", units = "mins") %>%
as_hms()
d
# 00:13:53
Upvotes: 3
Reputation: 388807
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"
Upvotes: 2