rdatetimedst

R - Get Daylight Saving Beginning and Ending from year


My question is fairly simple, yet I didn't really find an answer for it.

I want to write a function like so:

get_dst <- function(y = 2019){

}

y is the year input of the function

the ouput should be a list or a vector of datetimes that represent European Daylight Saving Times start and end.

For 2019 the output would be:

31-03-2019 02:00:00, 27-10-2019 03:00:00

for 2020 the output would be:

29-03-2020 02:00:00, 25-10-2019 03:00:00

Also I think dplyr should have a way to handle them when grouping on a variable that is a datetime because it is hard to work with them.


Solution

  • Within the function, we could create a sequence and apply dst to return TRUE/FALSE, subset and get the range

    get_dst <- function(y = 2019, tz){
             start <- paste0(y, '-01-01')
             end <- paste0(y, '-12-31')
             d1 <- seq(as.POSIXct(start, tz = tz),
                  as.POSIXct(end, tz =tz), by = 'hour')
             range(d1[lubridate::dst(d1)])
      }
    
    get_dst(2019,  "America/New_York")