Search code examples
rdplyrtimezoneattr

Converting timezone using dplyr syntax and attr function


I am trying to convert time zone using only dplyr syntax and the attr function, without loading other packages.

Reprex:

dt1 <- as.POSIXct("2010-01-01 08:00:00", tz = "GMT")
dt <- seq(dt1, length = 10, by = "1 day")

I could convert into the right timezone using attr:

attr(dt, "tzone")
[1] "GMT"

attr(dt, "tzone") <- "Australia/Sydney" # convert to intended tz

What I am interested in though how could I incorporate attr in dplyr::mutate syntax?


Solution

  • As far as a chain-able solution is concerned (I assume that's what you mean by "using dplyr syntax"), you could use .POSIXct as in

    library(magrittr)
    dt %>% .POSIXct(tz = "Australia/Sydney")
    #[1] "2010-01-01 19:00:00 AEDT" "2010-01-02 19:00:00 AEDT"
    #[3] "2010-01-03 19:00:00 AEDT" "2010-01-04 19:00:00 AEDT"
    #[5] "2010-01-05 19:00:00 AEDT" "2010-01-06 19:00:00 AEDT"
    #[7] "2010-01-07 19:00:00 AEDT" "2010-01-08 19:00:00 AEDT"
    #[9] "2010-01-09 19:00:00 AEDT" "2010-01-10 19:00:00 AEDT"
    

    Here is a minimal dplyr::mutate example

    data.frame(dt = dt) %>%
        mutate(dt_Australia = .POSIXct(dt, tz = "Australia/Sydney"))
    #                    dt        dt_Australia
    #1  2010-01-01 08:00:00 2010-01-01 19:00:00
    #2  2010-01-02 08:00:00 2010-01-02 19:00:00
    #3  2010-01-03 08:00:00 2010-01-03 19:00:00
    #4  2010-01-04 08:00:00 2010-01-04 19:00:00
    #5  2010-01-05 08:00:00 2010-01-05 19:00:00
    #6  2010-01-06 08:00:00 2010-01-06 19:00:00
    #7  2010-01-07 08:00:00 2010-01-07 19:00:00
    #8  2010-01-08 08:00:00 2010-01-08 19:00:00
    #9  2010-01-09 08:00:00 2010-01-09 19:00:00
    #10 2010-01-10 08:00:00 2010-01-10 19:00:00