Search code examples
rdstdate-arithmeticposixct

POSIXct times around DST?


I want to subtract 1 day from a POSIX date and end up at the same time around DST.

For example, when I add a day:

> as.POSIXct('2009-03-08 23:00:00.000') + 86400
[1] "2009-03-09 23:00:00 EDT"

But when I go past, it offsets:

> as.POSIXct('2009-03-08 23:00:00.000') - 86400
[1] "2009-03-07 22:00:00 EST"

What's the best way to deal with absolute time differences around DST? Usually I deal with this by converting the times into strings and dealing with them separately so that DST isn't applied.


Solution

  • Your code is doing exactly what you asked it to do, because you didn't ask it to add or subtract one day, you asked it to add or subtract 24 hours. 24 hours (86400 seconds) before 2009-03-08 23:00:00 EDT is 2009-03-07 22:00:00 EST. I'm not familiar with the R libraries, but I am familiar with the POSIX functions that they wrap. If you take a POSIXct, decrease its day property by 1, and then "re-cast" it to POSIXct via POSIXlt ( to ensure that e.g. February -1st becomes January 31st) then you should be able to subtract one day reliably.