Christoph
Christoph

Reputation: 7063

Why is the time zone not set correctly from characters

I wonder, why R does not get the correct time zone. Do I miss something?

my_str <- c("2016-01-01 00:04:52 CET", "2016-01-01 00:09:52 CET", 
            "2016-01-01 00:18:04 CET", "2016-01-01 00:18:49 CET")
my_t <- as.POSIXct(my_str)
attributes(my_t)
# $class
# [1] "POSIXct" "POSIXt" 
# 
# $tzone
# [1] ""

my_t <- lubridate::ymd_hms(my_str)
attributes(my_t)
# $tzone
# [1] "UTC"
# 
# $class
# [1] "POSIXct" "POSIXt" 

This "solves" the problem but I wonder why I have to take care about the obvious:

my_t <- as.POSIXct(my_str, tz="CET")
attributes(my_t)
# $class
# [1] "POSIXct" "POSIXt" 
# 
# $tzone
# [1] "CET"

Upvotes: 0

Views: 43

Answers (1)

GGamba
GGamba

Reputation: 13680

The awesome anytime package solves the issue:

my_str <- c("2016-01-01 00:04:52 CET", "2016-01-01 00:09:52 CET", 
            "2016-01-01 00:18:04 CET", "2016-01-01 00:18:49 CET")
library(anytime)

my_t <- anytime(my_str)

attributes(my_t)
#> $class
#> [1] "POSIXct" "POSIXt" 
#> 
#> $tzone
#> [1] "Europe/Berlin"

Upvotes: 2

Related Questions