Home > other >  Deal with CEST tz with as.POSIXct
Deal with CEST tz with as.POSIXct

Time:08-12

I have this df

df <- structure(list(ID = 1:3, Timestamp = c("2022-08-09 22:01:45 UTC", "2022-08-09 22:01:56 UTC", "2022-08-09 22:02:04 UTC")), class = "data.frame", row.names = c(NA, -3L))

I would like to extract day to another column

Used this

mutate(Day = as.POSIXct(strftime(Timestamp, format="%Y-%m-%d"),  format = "%Y-%m-%d"))

But I got this

Timestamp           Day                
   <dttm>              <dttm>             
 1 2022-08-09 22:01:45 2022-08-10 00:00:00
 2 2022-08-09 22:01:56 2022-08-10 00:00:00
 3 2022-08-09 22:02:04 2022-08-10 00:00:00

I would like to get this

Timestamp           Day                
   <dttm>              <dttm>             
 1 2022-08-09 22:01:45 2022-08-09 00:00:00
 2 2022-08-09 22:01:56 2022-08-09 00:00:00
 3 2022-08-09 22:02:04 2022-08-09 00:00:00

My current time

as.POSIXct(Sys.Date(), format = "%Y-%m-%d %H:%M:%S" , optional = FALSE)
"2022-08-12 02:00:00 CEST"

I think I should deal with UTC and CEST time zone, but don't know how.

mutate(Day = as.POSIXct(strftime(Timestamp, format="%Y-%m-%d", tz = "CEST"),  format = "%Y-%m-%d"))

doesn't work.

CodePudding user response:

CET and CEST are defined via tz = "etc/GMT-1" and tz = "etc/GMT-2" respectively. Have a look at this question to find out why.

I'm not 100 % sure if I get your issue, but if it's only that you need Day to be in CEST instead of UTC, you can make use of lubridate::with_tz() followed by format() to specify the format of your timestamps to be displayed.

stamp_utc <- "2022-08-09 22:01:45 UTC"

stamp_cest <- stamp_utc |> strptime(format="%Y-%m-%d %H:%M:%S", tz = "UTC") |> lubridate::with_tz("etc/GMT-2") 
stamp_cest
#> [1] "2022-08-10 00:01:45  02"

day_cest <- format(stamp_cest, "%Y-%m-%d")
day_cest
#> [1] "2022-08-10"

# transfered to your dplyr pipe
df |> dplyr::mutate(Day = strptime(Timestamp, format="%Y-%m-%d %H:%M:%S", tz = "UTC") |> lubridate::with_tz("etc/GMT-2") |> format("%Y-%m-%d"))
#>   ID               Timestamp        Day
#> 1  1 2022-08-09 22:01:45 UTC 2022-08-10
#> 2  2 2022-08-09 22:01:56 UTC 2022-08-10
#> 3  3 2022-08-09 22:02:04 UTC 2022-08-10
  • Related