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
In the help page ?as.POSIXct
, for the tz
argument it says
A timezone specification to be used for the conversion, if one is required. System-specific (see time zones), but ‘""’ is the current timezone, and ‘"GMT"’ is UTC (Universal Time, Coordinated).
Does as.POSIXct(as.yearmon("2010-01-01"), tz="GMT")
work for you?
After more perusal of the documentation, in the details section we see:
Dates without times are treated as being at midnight UTC.
So in your example, the tz
argument is ignored. If you use as.POSIXlt
it is easier to see what happens with the timezone. The following should all give the same answer, with UTC as the timezone.
unclass(as.POSIXlt(as.yearmon("2010-01-01")))
unclass(as.POSIXlt(as.yearmon("2010-01-01"), tz = "UTC"))
unclass(as.POSIXlt(as.yearmon("2010-01-01"), tz = "GMT"))
unclass(as.POSIXlt(as.yearmon("2010-01-01"), tz = "CET"))
In fact, since you are using as.yearmon
(which strips the time out) you will never get to set the timezone. Compare, e.g.,
unclass(as.POSIXlt(as.yearmon("2010-01-01 12:00:00"), tz = "CET"))
unclass(as.POSIXlt("2010-01-01 12:00:00", tz = "CET"))
You are setting the timezone correctly in your code. The problem you are perceiving is only at the output stage. POSIX values are all referenced to UTC/GMT. Dates are assumed to be midnight times. Midnight UTC is 1 AM CET ( which is apparently where you are).
> as.POSIXct(as.yearmon("2010-01-01"), tz="UTC")
[1] "2009-12-31 19:00:00 EST" # R reports the time in my locale's timezone
> dtval <- as.POSIXct(as.yearmon("2010-01-01"), tz="UTC")
> format(dtval, tz="UTC") # report the date in UTC note it is the correct date ... there
[1] "2010-01-01"
> format(dtval, tz="UTC", format="%Y-%m-%d ")
[1] "2010-01-01 " # use a format string
> format(dtval, tz="UTC", format="%Y-%m-%d %OS3")
[1] "2010-01-01 00.000" # use decimal time
See ?strptime
for many, many other format possibilities.
This seems to be an oddity with the date/time "POSIXct"
class methods. Try formatting the "Date"
or "yearmon"
variable first so that as.POSIXct.character
rather than as.POSIXct.{Date, yearmon}
is dispatched:
Date
> d <- as.Date("2010-01-01")
> as.POSIXct(format(d), tz = "UTC")
[1] "2010-01-01 UTC"
yearmon
> library(zoo)
> y <- as.yearmon("2010-01")
> as.POSIXct(format(y, format = "%Y-%m-01"), tz = "UTC")
[1] "2010-01-01 UTC"
> # or
> as.POSIXct(format(as.Date(y)), tz = "UTC")
[1] "2010-01-01 UTC"
This is because as.POSIXct.Date
doesn't pass ...
to .POSIXct
.
> as.POSIXct.Date
function (x, ...)
.POSIXct(unclass(x) * 86400)
<environment: namespace:base>