rdatetime

How can I add one day in a datetime value


How can I add one day in a datetime in R?

structure(list(timestamp = structure(1667523601, tzone = "UTC", class = c("POSIXct", 
"POSIXt"))), class = "data.frame", row.names = c(NA, -1L))

Solution

  • 1) Add seconds If xx is the input then add one day's worth of seconds. This works because POSIXct is internally expressed in seconds and R does not use leap seconds (although it does have a builtin vector, .leap.seconds, available). No packages are used.

    xx$timestamp
    ## [1] "2022-11-04 01:00:01 UTC"
    
    xx$timestamp + 24 * 60 * 60
    ## [1] "2022-11-05 01:00:01 UTC"
    

    2) POSIXlt Another way is to convert it to POSIXlt, add one to the mday component and then convert back. No packages are used.

    lt <- as.POSIXlt(xx$timestamp)
    lt$mday <- lt$mday + 1
    as.POSIXct(lt)
    ## [1] "2022-11-05 01:00:01 UTC"
    

    3) seq seq with by = "day" can be used. No packages are used.

    do.call("c", lapply(xx$timestamp, function(x) seq(x, length = 2, by = "day")[2]))
    ## [1] "2022-11-05 01:00:01 UTC"
    

    If we knew that there was only one element in timestamp it could be simplified to

    seq(xx$timestamp, length = 2, by = "day")[2]
    ## [1] "2022-11-05 01:00:01 UTC"
    

    4) lubridate The lubridate package supports adding days like this:

    library(lubridate)
    
    xx$timestamp + days(1)
    ## [1] "2022-11-05 01:00:01 UTC"
    

    Note

    The input shown in the question is:

    xx <- structure(list(timestamp = structure(1667523601, tzone = "UTC", 
      class = c("POSIXct", "POSIXt"))), 
      class = "data.frame", row.names = c(NA, -1L))