Change timezone in a POSIXct object

RDatetime

R Problem Overview


Playing with dateTimes and timezone can be tricky in R. Here is my question: I want to change the time-zone on a POSIXct object

R) data <- data.frame(x=c(1,2),dateTime=as.POSIXct(c("2010-03-11 03:30:00.432","2010-03-15 03:30:00.432"),format="%Y-%m-%d %H:%M:%S",tz="America/Montreal"))
R) data
  x            dateTime
1 1 2010-03-11 03:30:00
2 2 2010-03-15 03:30:00
R) str(data)
'data.frame':   2 obs. of  2 variables:
 $ x       : num  1 2
 $ dateTime: POSIXct, format: "2010-03-11 03:30:00" "2010-03-15 03:30:00"

But if I want to change the timezone, the only thing I found is:

R) data$dateTime2 = format(data$dateTime,tz="Europe/Paris")
R) str(data)
'data.frame':   2 obs. of  3 variables:
 $ x        : num  1 2
 $ dateTime : POSIXct, format: "2010-03-11 03:30:00" "2010-03-15 03:30:00"
 $ dateTime2: chr  "2010-03-11 09:30:00" "2010-03-15 08:30:00"

Or

R) data$dateTime2 = as.POSIXlt(data$dateTime,tz="Europe/Paris")
R) str(data)
'data.frame':   2 obs. of  3 variables:
 $ x        : num  1 2
 $ dateTime : POSIXct, format: "2010-03-11 03:30:00" "2010-03-15 03:30:00"
 $ dateTime2: POSIXlt, format: "2010-03-11 09:30:00" "2010-03-15 08:30:00"

God (or somebody on SO) knows why it doesn't work with POSIXct

R) data$dateTime2 = as.POSIXct(data$dateTime,tz="Europe/Paris")
R) str(data)
'data.frame':   2 obs. of  3 variables:
 $ x        : num  1 2
 $ dateTime : POSIXct, format: "2010-03-11 03:30:00" "2010-03-15 03:30:00"
 $ dateTime2: POSIXct, format: "2010-03-11 03:30:00" "2010-03-15 03:30:00"

Do I need to convert to character and cast back to POSIXct ?

R Solutions


Solution 1 - R

It doesn't work with POSIXct because base::as.POSIXct.default simply returns x if it's already POSIXct. You can change the timezone via the tzone attribute:

attr(data$dateTime, "tzone") <- "Europe/Paris"

Solution 2 - R

In the lubridate package there is a function with_tz which changes the timezone attribute (effectively what Joshua described).

dttm <- as.POSIXct("2016-01-01 10:10:10", tz = "UTC")
dttm
[1] "2016-01-01 10:10:10 UTC"

Change timezone from UTC to CET

with_tz(dttm, "CET")
[1] "2016-01-01 11:10:10 CET"

Solution 3 - R

As of 7/23/2021. indexTZ is deprecated. tzone is good to use.

tzone(data$dateTime) <- "Europe/Paris"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstatquantView Question on Stackoverflow
Solution 1 - RJoshua UlrichView Answer on Stackoverflow
Solution 2 - RMark HeckmannView Answer on Stackoverflow
Solution 3 - Ray__yaView Answer on Stackoverflow