How to identify the length of time between two dates in R
If you are finding the length of time (in hours) between two columns of dates in a dataframe:
> df$yourLength <- round(int_length(interval( df$yourStartTime, df$yourEndTIme)) / 60 / 60, digits = 2) |
… or …
If you are finding the length of time (in hours) between two datetimes in standard text form:
> yourLength = round(int_length(interval(“2020-1-1 12:30:00”, “2020-1-2 2:45:00”)) / 60 / 60, digits = 2) |
Note: This solution requires the lubridate package.
Explanation:
int_length returns the number of seconds between two dates in an interval. You must divide the number of seconds by 60 to get the number of minutes in the interval and again by 60 to get the number of hours in the interval. You could also get the number of hours by dividing the return value of int_length by 120.