66

我想为 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 对象添加几个小时?

4

3 回答 3

103

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"
于 2012-08-12T12:35:03.583 回答
73

lubridate包还通过便利功能等很好地实现了这hours一点minutes

x = Sys.time()
library(lubridate)
x + hours(3) # add 3 hours
于 2015-10-27T03:04:18.477 回答
7

James 和 Gregor 的答案很棒,但他们处理夏令时的方式不同。这是对它们的详细说明。

# 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 或其他不遵守夏令时的时区,这两种方法应该是相同的。

于 2020-01-24T16:55:55.347 回答