How to calculate number of days between two dates in R

Jazzmine picture Jazzmine · Mar 25, 2016 · Viewed 25.6k times · Source

I'm trying to subtract two dates in R. These are the two dates via the structure command:

str(standard_data_4testing$start_datetime)
 POSIXct[1:489124], format: "2016-02-01 00:38:49" "2016-02-01 07:48:53" "2016-02-01 08:32:08" "2016-02-01 11:21:13" ...

str(standard_data_4testing$original_installdate)
 Date[1:489124], format: "2015-10-15" "2015-10-15" "2015-10-15" "2016-01-29" "2016-01-29" "2016-01-29" ...

I created both with as.Date functions in R but start_datetime has date and time and original_installdate only has date in the original data as reflected above.

Is there a way to subtract them?

I tried to subtract using this statement:

standard_data_4testing$start_datetime - standard_data_4testing$original_installdate

but I get this error:

Warning message: Incompatible methods ("-.POSIXt", "-.Date") for "-"

after it prints out some data:

[6049] "2016-02-01 09:48:44 UTC" "2016-02-01 07:24:08 UTC" "2016-02-01 09:02:33 UTC" "2016-02-01 09:14:29 UTC" [6053] "2016-02-01 10:49:46 UTC" "2016-02-01 19:07:52 UTC" "2016-02-01 02:39:04 UTC" "2016-02-01 03:59:29 UTC" [6057] "2016-02-01 07:13:05 UTC" "2016-02-01 07:58:50 UTC" NA

I've also tried using POSIXct but received a similar error.

Is there any way I can subtract the two dates, despite the differences in their components?

Thanks for your help

Answer

snaut picture snaut · Sep 16, 2016

Convert both dates to the POSIXct class first. Be sure to do the calculations in the same timezone, the POSIXt classes default to your locale timezone, as.Date does not use a timezone when converting from character to Date.

test1 <- as.Date("2016-01-01")
test2 <- strptime("2016-01-02", format="%Y-%m-%d", tz="UTC")
difftime(as.POSIXct(test2), as.POSIXct(test1, tz="UTC"), units="days")
# Time difference of 1 days

When converting Dates from POSIXct to Date always give the timezone as an argument explicitly, since as.Date.POSIXct seems to ignore the timezone from the POSIXct object, as you see in this example (this might be platform dependent):

x <- as.POSIXct("2020-02-22 00:05", tz="CET")
as.Date(x)
as.Date(x, tz="UTC")
as.Date(x, tz="CET")