R - 从年份开始和结束获取夏令时

R - Get Daylight Saving Beginning and Ending from year

我的问题很简单,但我并没有真正找到答案。

我想写一个这样的函数:

get_dst <- function(y = 2019){

}

y 是函数的年份输入

输出应该是表示欧洲夏令时开始和结束的日期时间列表或向量。

2019 年的输出为:

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

2020 年的输出将是:

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

此外,我认为 dplyr 应该有办法在对日期时间变量进行分组时处理它们,因为很难使用它们。

在函数中,我们可以创建一个序列并将 dst 应用到 return TRUE/FALSE,子集并得到 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")

clock 包实际上公开了一种方法,可以通过 sys_time_info() 获得给定特定时间点的 previous/next 夏令时边界。我们可以使用它来获取特定年份的所有 DST 边界。

library(clock)

dst_boundaries <- function(year, zone) {
  # [start, end)
  # example: [2021-01-01, 2022-01-01)
  start <- date_time_build(year, zone = zone)
  end <- date_time_build(year + 1L, zone = zone)
  
  start <- as_sys_time(start)
  end <- as_sys_time(end)
  
  # An empty vector of date-times that we will add boundaries to
  boundaries <- .POSIXct(double(), tz = zone)
  
  repeat {
    # Look up DST info based on the current `start`.
    # It'll find the previous and next DST boundary.
    info <- sys_time_info(start, zone)
    boundary <- info$end
    
    # Is the DST boundary outside this year? If so, we are done.
    if (boundary >= end) {
      break
    }
    
    # Otherwise add it to our growing list of boundaries
    boundaries <- c(boundaries, as.POSIXct(boundary, tz = zone))
    start <- boundary
  }
  
  boundaries
}

dst_boundaries(2019, "America/New_York")
#> [1] "2019-03-10 03:00:00 EDT" "2019-11-03 01:00:00 EST"

# Apia, Samoa stopped using DST halfway through 2021
dst_boundaries(2020, "Pacific/Apia")
#> [1] "2020-04-05 03:00:00 +13" "2020-09-27 04:00:00 +14"
dst_boundaries(2021, "Pacific/Apia")
#> [1] "2021-04-04 03:00:00 +13"