Search code examples
rlubridate

In R how do I shift a time series dataframe forward by 8 hours?


Hi I have a df like this:

Timestamp            | Price  |
2019-04-30T11:00:00  |  5150  |
2019-04-30T12:00:00  |  5185  |
2019-04-30T13:00:00  |  5212  |
2019-04-30T14:00:00  |  5211  |

where typeof(df$Timestamp) returns "character"

How do I shift the Timestamp forward by 8 hrs? Expected result:

Timestamp            | Price  |
2019-04-30T19:00:00  |  5150  |
2019-04-30T20:00:00  |  5185  |
2019-04-30T21:00:00  |  5212  |
2019-04-30T22:00:00  |  5211  |

Solution

  • We can convert to datetime class and add the hours

    library(lubridate)
    df1$Timestamp <- ymd_hms(df1$Timestamp) +  hours(8)
    

    data

    df1 <- structure(list(Timestamp = c("2019-04-30T11:00:00", "2019-04-30T12:00:00", 
    "2019-04-30T13:00:00", "2019-04-30T14:00:00"), Price = c(5150L, 
    5185L, 5212L, 5211L)), class = "data.frame", row.names = c(NA, 
    -4L))