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
How to Generate Ascii "Graphical Output" from R
How to Put Exact Number of Decimal Places on Label Ggplot Bar Chart
Function for Retrieving Own Ip Address from Within R
Using ':=' in Data.Table to Sum the Values of Two Columns in R, Ignoring Nas
In R, Extract Part of Object from List
How to Create 3D - Matlab Style - Surface Plots in R
Summarise_At Using Different Functions for Different Variables
Vary Colors of Axis Labels in R Based on Another Variable
How to Suppress Automatic Table Name and Number in an .Rmd File Using Xtable or Knitr::Kable
Matching Multiple Columns on Different Data Frames and Getting Other Column as Result
Extract Knots, Basis, Coefficients and Predictions for P-Splines in Adaptive Smooth
Apply Function to Each Column in a Data Frame Observing Each Columns Existing Data Type
How to Display Verbatim Inline R Code with Backticks Using Rmarkdown
Using Rcpp Functions Inside of R's Par*Apply Functions from the Parallel Package