Adding time to POSIXct object in R

82,011

Solution 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"

Solution 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

Solution 3

James and Gregor's answers are great, but they handle daylight saving differently. Here's an elaboration of them.

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

So, either answer is correct depending on what you want. Of course, if you're using UTC or some other timezone that doesn't observe daylight saving, these two methods should be the same.

Share:
82,011
BlueTrin
Author by

BlueTrin

Working in an investment bank, writing analytics for Fixed Income products in a combination of C++, C# and Python.

Updated on April 09, 2021

Comments

  • BlueTrin
    BlueTrin about 3 years

    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 ?

  • sdittmar
    sdittmar over 5 years
    Gregors' solution will take care of daylight saving time. James' solution will not!