2

I'm using lubridate to perform several operations on dates, and at some point I need to add 6 days to date I'm working with. I'm doind this in a loop and it works for almost every date, but on this specific one the sum returns NA

library(lubridate)
testDate <- ymd("2018-10-29", tz = "America/Sao_Paulo")

testDate + days(4) #OK
testDate + days(5) #OK
testDate + days(6) #Returns NA
testDate + days(7) #OK
testDate + days(8) #OK
testDate + days(9) #OK

Can someone help me understand why is this happening?

Session Info:

R version 3.6.0 (2019-04-26)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] lubridate_1.7.4

loaded via a namespace (and not attached):
[1] compiler_3.6.0 magrittr_1.5   tools_3.6.0    Rcpp_1.0.3     stringi_1.4.3  stringr_1.4.0 
Fino
  • 1,774
  • 11
  • 21
  • 2
    have you checked the daylight savings – akrun May 26 '20 at 21:39
  • 1
    Related: [Handling dates when we switch to daylight savings time and back](https://stackoverflow.com/questions/13865172/handling-dates-when-we-switch-to-daylight-savings-time-and-back) – Henrik May 26 '20 at 22:55

1 Answers1

3

As @akrun suggested, this is an issue with daylight savings time. Looking at the days before and after the 6:

format(testDate + days(c(5,7)), format = "%Y-%m-%d %H:%M:%S")
# [1] "2018-11-03 00:00:00" "2018-11-05 00:00:00"

You'll notice that it assumes "midnight" (as one might expect).

In São Paulo, Brazil in 2018, it rolled forward at midnight on the 4th (ref) at midnight:

When local standard time was about to reach Sunday, November 4, 2018, 12:00:00 midnight clocks were turned forward 1 hour to Sunday, November 4, 2018, 1:00:00 am local daylight time instead.

That means that Nov 3, 23:59:59 existed, but as soon as it ticked forward a second, it became Nov 4, 01:00:00. Which suggests that (mathematically) Nov 3, 00:00:00 never existed.

Because of that, R tells you that that timestamp is not a legitimate time by returning NA.

You can, however, deal with Date objects quite easily:

testDate + days(5:7)
# [1] "2018-11-03 -03" NA               "2018-11-05 -02"

as.Date(testDate) + days(5:7)
# [1] "2018-11-03" "2018-11-04" "2018-11-05"
r2evans
  • 141,215
  • 6
  • 77
  • 149