1

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?

smci
  • 32,567
  • 20
  • 113
  • 146
Satya
  • 1,708
  • 1
  • 15
  • 39
  • 3
    You gained an hour due to Daylight Savings Time changeover on Sunday 10/30/2005 02:00:00. You can see the difference is 25h between 10/29/2005 and 10/30/2005 – smci May 20 '18 at 05:57
  • 1
    @smci is correct. using `tz="UTC"` will fix the problem. – MKR May 20 '18 at 06:00
  • 1
    It's not necessarily wrong, it depends what timezone this is supposed to be. But UTC makes things unambiguous. – smci May 20 '18 at 06:01
  • @smci, thanks! That was a subtle mistake in my code!! – Satya May 20 '18 at 06:03
  • Related: [POSIXct times around DST?](https://stackoverflow.com/questions/1395499/posixct-times-around-dst) and there are [213 questions about \[r\] DST](https://stackoverflow.com/search?q=%5Br%5D+DST). This is probably a duplicate – smci May 20 '18 at 06:06
  • Reminds me of riddles like *"Where did the plane go for the missing hour?"* – smci May 20 '18 at 06:12

1 Answers1

2

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
smci
  • 32,567
  • 20
  • 113
  • 146