[R] Converting Date or chron to POSIXt

Gabor Grothendieck ggrothendieck at myway.com
Mon Apr 26 15:20:54 CEST 2004



Everything below was done on Windows XP Pro using R 1.9.0:

Problem 1. 

Converting objects of class Date to POSIXlt appears not to set 
the isdst component as expected:

> # converting a Date to a POSIXlt, at first, appears to work as expected
> as.POSIXlt(as.Date("2004-10-16"))
[1] "2004-10-16"

> # but upon conversion to POSIXct its off by one hour
> as.POSIXct(as.POSIXlt(as.Date("2004-10-16")))
[1] "2004-10-16 01:00:00 Eastern Daylight Time"

> # the isdst component from the first line is 0
> unclass(as.POSIXlt(as.Date("2004-10-16")))$isdst
[1] 0

> # the isdst component if converted directly from character is 1
> as.POSIXlt("2004-10-16")
[1] "2004-10-16"
> unclass(as.POSIXlt("2004-10-16"))$isdst
[1] 1


> # Problem 2.

> # in converting Date directly to POSIXct it appears that the
> # timezone is assumed to be GMT and specifying the tz= arg does
> # not appear to have any effect:

> as.POSIXct(as.Date("2004-10-16"))
[1] "2004-10-15 20:00:00 Eastern Daylight Time"

> # specifying tz="" gives same result
> as.POSIXct(as.Date("2004-10-16"),tz="")
[1] "2004-10-15 20:00:00 Eastern Daylight Time"

> # specifying tz="GMT" gives same result
> as.POSIXct(as.Date("2004-10-16"),tz="GMT")
[1] "2004-10-15 20:00:00 Eastern Daylight Time"

> # The same thing happens when attempting to convert from chron

> # convert chron date to POSIXct
> as.POSIXct(chron("10/16/2004"))
[1] "2004-10-15 20:00:00 Eastern Daylight Time"

> # specify GMT
> as.POSIXct(chron("10/16/2004"),tz="GMT")
[1] "2004-10-15 20:00:00 Eastern Daylight Time"

> # specify current timezone
> as.POSIXct(chron("10/16/2004"),tz="")
[1] "2004-10-15 20:00:00 Eastern Daylight Time"

My current workaround is to convert Date or chron
objects to character and then convert the character
representation:

> # format chron date and then convert.  Now its ok.
> options(chron.year.abb=F)
> as.POSIXct( format( chron("10/15/2004"), "y-m-d") )
[1] "2004-10-15 Eastern Daylight Time"

> # format Date date and then convert.  Now its ok.
> as.POSIXct( format( as.Date("2004-10-15")) )
[1] "2004-10-15 Eastern Daylight Time"




More information about the R-help mailing list