Search code examples
rdatetimeposixlubridate

Converting time to POSIX after forcing time zone


I have vector of times:

library(lubridate)
> test
[1] "2018-01-13 22:23:00 UTC" "2018-01-13 22:23:00 UTC" "2018-01-13 22:23:00 UTC" "2018-01-13 22:23:00 UTC"
[5] "2018-01-13 22:23:00 UTC" "2018-01-13 22:23:00 UTC"

All of the class POSIX:

> class(test)
[1] "POSIXct" "POSIXt" 

However when I force conversion of time zone:

test <- format(force_tz(test, tz = 'UTC'), tz ='America/Los_Angeles', usetz=TRUE)

This also forces the time vectors into a character class which cannot be converted back to POSIX.

> class(test)
[1] "character"
as.POSIXct(test, format = "%Y-%m-%d HH:MM:SS")
[1] NA NA NA NA NA NA

What could be the issue here and what is the workaround to changing timezone and retaining POSIX class?


Solution

  • lubridate based answer using with_tz

    ss <- strptime(test,format = "%Y-%m-%d %H:%M:%S", tz = 'UCT')
    lubridate::with_tz(ss, "America/Los_Angeles")
    

    Output:

    > test <- "2018-01-13 22:23:00 UTC"
    > ss <- strptime(test,format = "%Y-%m-%d %H:%M:%S", tz = 'UCT')
    > lubridate::with_tz(ss, "America/Los_Angeles")
    [1] "2018-01-13 14:23:00 PST"
    

    Please note I've used strptime since my input is a text but in your case you can just simply use with_tz