【问题标题】:missing hour in seq function generating time in R?R中的seq函数生成时间缺少小时?
【发布时间】:2014-06-29 23:09:03
【问题描述】:

我在使用 R 生成正确的时间序列时遇到问题:

fivemin <- seq(as.POSIXct("2014/01/01 0:00:00"), as.POSIXct("2014/04/01 0:00:00"), by="5 mins",tz="EST")
time <- data.frame(MasterTime=fivemin)

使用上面的代码,我可以得到一个包含 25909 个观测值的数据框。但是,在东部标准时间(没有夏令时)下,观测数应为 25920。与 20014 年 3 月 9 日夏令时转换的时间差为 1 小时,因为那时时间将从凌晨 1 点变为 3 点直接上午。我不确定 R 如何处理这种时间变化。如何修改我的代码,以便 R 生成一个时间序列,而不会在 2014 年 3 月 9 日凌晨 2 点丢失?有人对此有任何想法吗?

非常感谢!

【问题讨论】:

  • as.POSIXct中明确设置时区。
  • 您也可以使用Sys.setenv(TZ='EST') 在会话期间忽略夏令时。

标签: r time posixct seq


【解决方案1】:

如果您不想使用夏令时,请尝试设置 tz = 'UTC'

fivemin <- seq(as.POSIXct("2014/01/01 0:00:00", tz = 'UTC'), as.POSIXct("2014/04/01 0:00:00", tz = 'UTC'), by="5 mins")
head(fivemin)
length(fivemin)
#[1] 25921

除了“UTC”或“GMT”外,最好不要使用三个字母来表示时区,例如“EST”,因为它们不明确。澳大利亚和美国一样有东部标准时间。而是使用国家/城市

fivemin <- seq(as.POSIXct("2014-04-06 2:00:00", tz="Australia/Melbourne"), as.POSIXct("2014-04-06 3:00:00", tz="Australia/Melbourne"), by="5 mins")
length(fivemin)
# [1] 25   
# Melbourne's DST finished on 6 April 2014 at 3 am so there are 25 x 5 min periods in the hour between 2am and 3 am 


fivemin <- seq(as.POSIXct("2014-04-06 2:00:00", tz="Australia/Brisbane"), as.POSIXct("2014-04-06 3:00:00", tz="Australia/Brisbane"), by="5 mins")
length(fivemin)
# [1] 13  Brisbane doesn't use DST so no problem

还要检查lubridate 包中的dst 函数。

如果您想保留时区,但使用标准时间,请尝试类似的方法。

library(lubridate)
fivemin <- seq(as.POSIXct("2014-04-06 2:00:00", tz="Australia/Melbourne"), as.POSIXct("2014-04-06 3:00:00", tz="Australia/Melbourne"), by="5 mins")
fivemin[dst(fivemin)] <- fivemin[dst(fivemin)]-3600

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    相关资源
    最近更新 更多