在R中向POSIXct对象添加时间

76
我想给一个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对象中?

3个回答

111

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"

81

lubridate 包也使用方便的函数 hours, minutes 等来实现这一点。

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

4
格雷戈尔的解决方案将处理夏令时问题,而詹姆斯的解决方案则不会。 - sdittmar

8

詹姆斯和格雷戈的回答非常好,但他们处理夏令时的方法不同。这里对它们进行了详细的阐述。

# 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)

因此,答案取决于您的需求。当然,如果您使用协调世界时或其他不遵守夏令时的时区,则这两种方法应该是相同的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接