[R] time zones and the chron to POSIXct conversion

Gabor Grothendieck ggrothendieck at gmail.com
Sat Jun 16 15:58:52 CEST 2012


On Fri, Jun 15, 2012 at 3:25 AM, Jannis <bt_jannis at yahoo.de> wrote:
> Hey R folks,
>
>
> i found some strange (to me) behaviour with chron to POSIXct conversion. The
> two lines of code result in two different results, on ewith the correct time
> zone, one without:
>
> library(chron)
> as.POSIXct(chron('12/12/2000'), tz = 'UTC')
> as.POSIXlt(chron('12/12/2000'), tz = 'UTC')
>
> Only the code below would give me a POSIXct object with the correct time
> zone:
>
> as.POSIXct(as.POSIXlt(chron('12/12/2000'), tz = 'UTC'))
>
>
> Is this a bug or desired behaviour?

The time zone aspect of these conversions can be tricky and its
generally safer to convert to a character representation first and
then from there convert to the desired class.  Here we first convert
it to Date class since Date's default character format is similar to
POSIXct's and then convert to character.  Note that up to this point
it does not involve time zones.  Finally we apply as.POSIXct.

> cc <- chron("12/12/2000")
> as.POSIXct(format(as.Date(cc)), tz = "UTC")
[1] "2000-12-12 UTC"

There is a table at the end of the help desk article of R News 4/1
which shows how to do various conversions between various classes.
Although the article is quite old most of it still works.

There is also some question here of whether POSIXct is really the
appropriate class in the first place.  Suggest you read the
aforementioned article for some pointers on that.

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list