Search code examples
rdstdate-arithmeticposixctdifftime

Possible bug in `difftime` - calculating difference in date time in R


I am calculating differences in two date times, using the difftime function in R and getting a wrong answer, here is the code

t1 <- as.POSIXct("7/18/2005 8:30:00", format = "%m/%d/%Y %H:%M:%S")
t2 <- as.POSIXct("10/30/2005 8:30:00", format = "%m/%d/%Y %H:%M:%S")
difftime(t2,t1,units = "hours") 

I am getting the following answer

Time difference of 2497 hours

which I know is wrong, as both t1 and t2 have the same time value, so they should be separated by an exact multiple of 24 hours (i.e., the correct answer is 2496 hours, not 2497 - also confirmed by other tools such as excel, google sheets).

Any idea, why R is giving me the wrong result?


Solution

  • You gained an hour due to Daylight Savings Time changeover (Sunday 10/30/2005 02:00:00)

    You can modify this by doing as.POSIXct(..., tz = 'UTC') with whatever timezone it's supposed to be; UTC to make things unambiguous and avoid DST changes.

    If you want to modify the default timezone for all as.POSIXct() calls, see How to change the default time zone in R?, which suggests:

    • [as an R command] Sys.setenv(TZ='GMT') or
    • [R setup file] edit TZ="UTC"into Renviron.site