Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate number of days between two dates in R

Tags:

r

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?

like image 909
Jazzmine Avatar asked Mar 25 '16 17:03

Jazzmine


People also ask

How many days are in a year r?

16.4. Larger units are created by converting minutes, hours, days, weeks, and years to seconds at the standard rate (60 seconds in a minute, 60 minutes in an hour, 24 hours in day, 7 days in a week, 365 days in a year).

What is POSIXct format in R?

POSIXct stores date and time in seconds with the number of seconds beginning at 1 January 1970. Negative numbers are used to store dates prior to 1970. Thus, the POSIXct format stores each date and time a single value in units of seconds. Storing the data this way, optimizes use in data.


1 Answers

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")
like image 103
snaut Avatar answered Oct 19 '22 05:10

snaut