9
votes

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

1
Can the time component in the first format be neglected? - DatamineR
message says one of them is` POSIxt` and the other Date. If they are the same class, you can subtract. - Kota Mori
DatamineR - that is an interesting idea. I will try to remove it as I define it .asDate and see if that helps. I tried that and received the same error still: Warning message: Incompatible methods ("-.POSIXt", "-.Date") for "-" - Jazzmine
@Jazzmine: don't use str, use dput to give us a reproducible example - digEmAll
Anyway, you can use difftime function difference <- difftime(dates1,dates2,units='days'), and get a numeric using as.numeric(difference) (N.B. difftime it automatically converts Date's to POSIXct) - digEmAll

1 Answers

11
votes

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")