结合 POSIXct 会给出错误的时间

combining POSIXct gives wrong hours

我有一个日期列表,我试图在 Reduce 上使用这些日期,并意识到当我组合这些向量时,时间正在改变。这是一个例子:

x = structure(1315714440, tzone = "UTC", class = c("POSIXct", "POSIXt"))
y = structure(1325832660, tzone = "UTC", class = c("POSIXct", "POSIXt"))
x
[1] "2011-09-11 04:14:00 UTC"
y
[1] "2012-01-06 06:51:00 UTC"
c(x,y)
[1] "2011-09-11 00:14:00 EDT" "2012-01-06 01:51:00 EST"

为什么会这样?对替代品有什么建议吗?

谢谢!

c.POSIXct 删除时区属性。来自 ?c.POSIXct

Using c [...] on "POSIXct" objects drops any "tzone" attributes (even if they are all marked with the same time zone).

因此,按照您的c(x,y),您可以使用attr恢复原来的UTC时区:

xy <- c(x, y)
attr(xy, "tzone") <- "UTC"
xy
# [1] "2011-09-11 04:14:00 UTC" "2012-01-06 06:51:00 UTC" 

Ripley 的更多背景资料:

c(a, b) for POSIXct objects with tzone attributes?

“我们考虑过 c() 保留时区,如果它对所有 对象,但主要问题是 c() 被记录为删除 属性:

c is sometimes used for its side effect of removing attributes except names, for example to turn an array into a vector. as.vector is a more intuitive way to do this, but also drops names. Note too that methods other than the default are not required to do this (and they will almost certainly preserve a class attribute).

所以,有时删除有时保留属性 令人困惑。

但无论如何,文档(?c.POSIXct)很清楚:

Using c on "POSIXlt" objects converts them to the current time zone, and on "POSIXct" objects drops any "tzone" attributes (even if they are all marked with the same time zone).

所以推荐的方法是添加一个“tzone”属性,如果你知道的话 你想要它是。 POSIXct 对象是绝对时间:时区 仅影响它们的转换方式(包括转换为打印字符)。"


一样,rbind可用作解决方法:

how to retain time zone when doing c(POSIXct)