【问题标题】:R - Prevent aggregate function from converting date time timezones to local time?R - 防止聚合函数将日期时区转换为本地时间?
【发布时间】:2020-06-06 06:33:59
【问题描述】:

有没有办法阻止aggregate 将日期时间转换为计算机的本地时区?例如:

dtUTC <- as.POSIXct(c('2010-01-01 01:01:01', '2015-01-02 07:23:11',
                      '2016-06-02 05:23:41', '2018-01-08 17:57:43'), tz='UTC')
groups <- c(1,1,2,2)
result <- aggregate(dtUTC, by=list(groups), FUN=min)

结果将转换为我的计算机本地时区。

> dtUTC
[1] "2010-01-01 01:01:01 UTC" "2015-01-02 07:23:11 UTC" "2016-06-02 05:23:41 UTC"
[4] "2018-01-08 17:57:43 UTC"
> result$x
[1] "2010-01-01 12:01:01 AEDT" "2016-06-02 15:23:41 AEST"

我可以事后将其转换回来,但这是一个烦人的额外步骤。特别是如果我有多个日期时间列。

attr(result$x, 'tzone') <- 'UTC'
> result$x
[1] "2010-01-01 01:01:01 UTC" "2016-06-02 05:23:41 UTC"

【问题讨论】:

    标签: r datetime timezone


    【解决方案1】:

    我找不到您可以使用 aggregate 执行的任何操作来更改此行为,但您可以设置环境的 TZ,以便任何日期时间将自动采用 UTC:

    Sys.setenv(TZ='UTC') # <- set your TZ here
    
    dtUTC <- as.POSIXct(c('2010-01-01 01:01:01', '2015-01-02 07:23:11',
                          '2016-06-02 05:23:41', '2018-01-08 17:57:43'))
    groups <- c(1,1,2,2)
    
    df <- data.frame(dtUTC, groups)
    result <- aggregate(dtUTC ~ groups, df, min)
    
    result$dtUTC
    
    # [1] "2010-01-01 01:01:01 UTC" "2016-06-02 05:23:41 UTC"
    

    【讨论】:

    • 谢谢@gersht。我赞成您的回答,因为这是一个很好的解决方案,但出于其他原因,我宁愿不更改环境的 tzone。
    【解决方案2】:

    你可以使用dplyr包聚合

    library(lubridate)
    library(dplyr)
    dtUTC <- as.POSIXct(c('2010-01-01 01:01:01', '2015-01-02 07:23:11',
                          '2016-06-02 05:23:41', '2018-01-08 17:57:43'), tz='UTC')
    groups <- c(1,1,2,2)
    b<-data.frame(date= dtUTC, group = groups) %>% group_by(group) %>% dplyr::summarise(min = min(date))
    b$min
    
    
    > b$min
    [1] "2010-01-01 01:01:01 UTC" "2016-06-02 05:23:41 UTC"
    

    【讨论】:

      猜你喜欢
      • 2021-05-02
      • 1970-01-01
      • 2019-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      • 1970-01-01
      相关资源
      最近更新 更多