Adding time to POSIXct object in R

前端 未结 3 2042
暖寄归人
暖寄归人 2020-12-08 09:27

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(pas         


        
相关标签:
3条回答
  • 2020-12-08 09:45

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

    x = Sys.time()
    library(lubridate)
    x + hours(3) # add 3 hours
    
    0 讨论(0)
  • 2020-12-08 09:45

    James and Gregor's answers are great, but they handle daylight savings 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 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)
    

    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 savings, these two methods should be the same.

    0 讨论(0)
  • 2020-12-08 09:58

    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"
    
    0 讨论(0)
提交回复
热议问题