Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

r - as.POSIXct gives an unexpected timezone

I'm trying to convert a yearmon date (from the zoo package) to a POSIXct in the UTC timezone. This is what I tried to do:

> as.POSIXct(as.yearmon("2010-01-01"), tz="UTC")
[1] "2010-01-01 01:00:00 CET"

I get the same when I convert a Date:

> as.POSIXct(as.Date("2010-01-01"),tz="UTC")
[1] "2010-01-01 01:00:00 CET"

The only way to get it to work is to pass a character as an argument:

> as.POSIXct("2010-01-01", tz="UTC")
[1] "2010-01-01 UTC"

I looked into the documentation of DateTimeClasses, tzset and timezones. My /etc/localtime is set to Europe/Amsterdam. I couldn't find a way to set the tz to UTC, other than setting the TZ environment variable:

> Sys.setenv(TZ="UTC")
> as.POSIXct(as.Date("2010-01-01"),tz="UTC")
[1] "2010-01-01 UTC"

Is it possible to directly set the timezone when creating a POSIXct from a yearmon or Date?

Edit:

I checked the functions as.POSIXct.yearmon. This one passes to the as.POSIXct.Date.

> zoo:::as.POSIXct.yearmon
function (x, tz = "", ...) 
as.POSIXct(as.Date(x), tz = tz, ...)
<environment: namespace:zoo>

So like Joshua says the timezone gets lost in the as.POSIXct.Date. For now I'll use Richies suggestion to set the tzone by hand using:

attr(x, "tzone") <- 'UTC'

This solves the issue of the lost tzone, which is only used for presentation and not internally like Grothendieck and Dwin suggested.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is because as.POSIXct.Date doesn't pass ... to .POSIXct.

> as.POSIXct.Date
function (x, ...) 
.POSIXct(unclass(x) * 86400)
<environment: namespace:base>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...