3

I am a bit confused by the function "difftime". When I calculate the time difference up to 27 March 2016 everything is ok. But as soon as I try 28, 29, 30 or 31 March 2016 there seems to be a problem:

> difftime("2016-03-27","1979-01-01", units="days")
Time difference of 13600 days
> difftime("2016-03-28","1979-01-01", units="days")
Time difference of 13600.96 days
> difftime("2016-03-31","1979-01-01", units="days")
Time difference of 13603.96 days

I can get around this problem by setting the date to 27 March 2016 and then adding manually the number of days "missing", but I was wondering if there is maybe something wrong with the function...? I don't really see what I could have done wrong since I just changed the day number...

user3270948
  • 35
  • 1
  • 4

2 Answers2

4

The reason an extra day in going from 2016-03-27 to 2016-03-28 is 0.96 is due to daylight savings time kicking in:

0.96 = 23 hours / 24 hours

Read this R Nabble blog which discusses this problem in detail.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

There is no problem, when you convert it with as.Date:

difftime(as.Date("2016-03-28"), as.Date("1979-01-01"), units="days")

# Time difference of 13601 days

Also there is no problem with lubridate:

library(lubridate)   
difftime(ymd("2016-03-28"), ymd("1979-01-01"), units="days")

# Time difference of 13601 days
J_F
  • 9,956
  • 2
  • 31
  • 55