Adding time to POSIXct object in R

夙愿已清 提交于 2019-12-29 03:32:09

问题


I would like to add 1 hour to a POSIXct object, but it does not support '+'.

This command:

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

returns this error:

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

How can I add a few hours to a POSIXct object ?


回答1:


POSIXct objects are a measure of seconds from an origin, usually the UNIX epoch (1st Jan 1970). Just add the requisite number of seconds to the object:

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"



回答2:


The lubridate package also implements this nicely with convenience functions hours, minutes, etc.

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


来源:https://stackoverflow.com/questions/11922181/adding-time-to-posixct-object-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!