Character Posixct Conversion in R Causes Wrong Timezone Values on Daylight Saving Time Transition (Cest/Cet))

Character POSIXct Conversion in R causes wrong timezone values on daylight saving time transition (CEST/CET))

Here's a work around that goes from POSIXct to character back to POSIXct preserving the original daylight savings time status.

Sys.setenv(TZ='Europe/Berlin') # to reproduce OP's example
time_seq_01 <- seq(as.POSIXct("2012-10-28 02:00:00"), by = 900, length.out = 10)
time_seq_02 <- format(time_seq_01,usetz = TRUE)

time_seq_02_lt <- as.POSIXlt(time_seq_02)
time_seq_02_lt$isdst <- as.POSIXlt(time_seq_01)$isdst
time_seq_03 <- as.POSIXct(time_seq_02_lt)

As far as I can tell, R's support for string-to-datetime doesn't include DST flags specified within the strings.

Handling of switch to daylight saving time with POSIXct in R

SOLUTION

Thanks to zoowalk and Roland in the comments for this solution:

My timeseries was recorded without time switches. However my OS time zone does record time switches throughout the year. Accordingly, I need to hand a time zone to the function that equally does not have time switches, like UTC:

as.POSIXct(xx, format = "%Y-%m-%d %H:%M", tz="UTC")

CET/CEST time shift is dropped when exporting from R to excel

Try like this:

require(openxlsx)
options("openxlsx.datetimeFormat" = "yyy-mm-dd hh:mm:ss %Z")

dd <- c("2019-03-31 01:00:00", "2019-03-31 03:00:00")
CEST_date <- as.POSIXlt(dd, tz = "CET")
CEST_date <- format(CEST_date, usetz = TRUE)
CEST_test <- as.data.frame(CEST_date)
write.xlsx(CEST_test,"CEST_test.xlsx")

POSIXct daylight saving issues (summertime)

Specify the timezone explicitly:

as.numeric(as.POSIXct('1970-01-01', tz = "GMT"))
## [1] 0

or set your entire session:

Sys.setenv(TZ = "GMT")
as.numeric(as.POSIXct('1970-01-01'))
## [1] 0
Sys.setenv(TZ = "")

Lubridate timezone handling

Try:

t0 = "2021-09-23 12:00:00"

library(lubridate)
#1

t1 = as_datetime(t0, tz = "Europe/Berlin")
[1] "2021-09-23 12:00:00 CEST"

or

#2
t1 = as_datetime(t0, tz = "CST6CDT")

[1] "2021-09-23 12:00:00 CDT"


Related Topics



Leave a reply



Submit