Search code examples
rzoneinfoposixct

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.


Solution

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

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