Reputation: 9
I need to get a difference between two dates(timestamps) in days such as (2021-03-08 00:01:01) - (2021-03-07 23:59:59)
will be equal to 1. I tried to use day() function, but there is a problem: if two dates have different month, it returns wrong result, such as (2021-03-01 12:12:12) - (2021-02-27 12:12:12)
will be equal to -26, but I need 2. Any ideas?
Upvotes: 0
Views: 62
Reputation: 7550
Try this:
max(df$date) - min(df$date)
This subtracts the minimum (earliest) date in the date
field from the maximum (latest) date in the date
field to produce an output of:
> max(df$date) - min(df$date)
Time difference of 28 days
Just make sure that the field df$date
is in date format:
df$date <- as.Date(df$date, format = "%d/%m/%Y")
Upvotes: 0
Reputation: 73802
Don't know how your dates are formatted, but try as.Date
-diff(as.Date(c("2021-03-08 00:01:01", "2021-03-07 23:59:59")))
# Time difference of 1 days
-diff(as.Date(c("2021-03-01 12:12:12", "2021-02-27 12:12:12")))
# Time difference of 2 days
If you just want the numbers wrap a as.numeric(...)
around it.
Upvotes: 1