在 R 中为 POSIXct 对象添加时间

我希望向 POSIXct 对象添加1小时,但它不支持“ +”。

这个命令:

as.POSIXct("2012/06/30","GMT")
+ as.POSIXct(paste(event_hour, event_minute,0,":"), ,"%H:%M:$S")

返回此错误:

Error in `+.POSIXt`(as.POSIXct("2012/06/30", "GMT"), as.POSIXct(paste(event_hour,  :
binary '+' is not defined for "POSIXt" objects

如何向 POSIXct 对象添加几个小时?

89046 次浏览

POSIXct对象是从原点(通常是 UNIX 纪元(1970年1月1日))开始的秒数。只需将所需的秒数添加到对象上:

x <- Sys.time()
x
[1] "2012-08-12 13:33:13 BST"
x + 3*60*60 # add 3 hours
[1] "2012-08-12 16:33:13 BST"

lubridate包还通过方便的函数 hoursminutes等很好地实现了这一点。

x = Sys.time()
library(lubridate)
x + hours(3) # add 3 hours

詹姆斯和格雷戈尔的回答很棒,但他们对夏令时的处理方式不同。

# Start with d1 set to 12AM on March 3rd, 2019 in U.S. Central time, two hours before daylight saving
d1 <- as.POSIXct("2019-03-10 00:00:00", tz = "America/Chicago")
print(d1)  # "2019-03-10 CST"


# Daylight saving begins @ 2AM. See how a sequence of hours works. (Basically it skips the time between 2AM and 3AM)
seq.POSIXt(from = d1, by = "hour", length.out = 4)
# "2019-03-10 00:00:00 CST" "2019-03-10 01:00:00 CST" "2019-03-10 03:00:00 CDT" "2019-03-10 04:00:00 CDT"


# Now let's add 24 hours to d1 by adding 86400 seconds to it.
d1 + 24*60*60  # "2019-03-11 01:00:00 CDT"


# Next we add 24 hours to d1 via lubridate seconds/hours/days
d1 + lubridate::seconds(24*60*60)  # "2019-03-11 CDT" (i.e. 2019-03-11 00:00:00 CDT)
d1 + lubridate::hours(24)          # "2019-03-11 CDT" (i.e. 2019-03-11 00:00:00 CDT)
d1 + lubridate::days(1)            # "2019-03-11 CDT" (i.e. 2019-03-11 00:00:00 CDT)

所以,两个答案中的任何一个都是正确的,这取决于你想要什么。当然,如果您使用的是 UTC 或其他一些不遵守夏令时的时区,那么这两种方法应该是相同的。