在R中为POSIXct对象添加时间

时间:2012-08-12 12:31:33

标签: r datetime 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对象添加几个小时?

3 个答案:

答案 0 :(得分:73)

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"

答案 1 :(得分:54)

lubridate包也可以通过便捷函数hoursminutes等实现这一点。

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

答案 2 :(得分:2)

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

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

# Daylight savings 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 libridate 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或其他不符合夏令时的时区,则这两种方法应该相同。