user1700890
user1700890

Reputation: 7742

Missing timezone value in POSIXct in R and local time

Here is my example:

my_time<- as.POSIXct("2020-02-01 06:20:09 UTC")

It creates POSIXct object and if I print its value I get

"2020-02-01 06:20:09 CST"

If I run

attributes(my_time)

I get back

$class
[1] "POSIXct" "POSIXt" 

$tzone
[1] ""

Why is zone empty, it clearly displayed when I printed variable value? So I am guessing it it is attaching local time zone. Can I prevent this behaviour?

Upvotes: 0

Views: 365

Answers (1)

Jan Janiszewski
Jan Janiszewski

Reputation: 452

Because there is no timezone you defined. Although you think you defined the timezone, actually as.POSIXct does not read the 'UTC' indicator in your string.

Therefore, as as.POSIXct does not find your timezone.

When you print the time, POSIXct does not find any timezone in the object and assumes that you mean your timezone if no timezone is defined. Therefore you get your computer timezone when printing the object.

For example, when I run your code, I get:

> my_time<- as.POSIXct("2020-02-01 06:20:09 UTC")
> my_time
[1] "2020-02-01 06:20:09 CET"

Therefore, you should define the timezone:

> my_time<- as.POSIXct("2020-02-01 06:20:09", tz='UTC')
> attributes(my_time)
$class
[1] "POSIXct" "POSIXt" 

$tzone
[1] "UTC"

Upvotes: 2

Related Questions