[R] as.Date question

Gabor Grothendieck ggrothendieck at gmail.com
Thu Dec 24 18:58:55 CET 2009


zzz1 is POSIXct so looking at:

> as.Date.POSIXct
function (x, ...)
{
    z <- floor(unclass(x)/86400)
    attr(z, "tzone") <- NULL
    structure(z, class = "Date")
}
<environment: namespace:base>

we see as.Date.POSIXct takes the POSIXct object, zzz1, and converts it
to Date relative to GMT.  There is no time zone argument on
as.Date.POSIXct and the time zone specification given to it is
ignored.

On the other hand as.Date.POSIXlt takes the POSIXlt object, zzz2, and
presumably just uses the components in it:

> str(unclass(zzz2))
List of 9
 $ sec  : num 0
 $ min  : int 0
 $ hour : int 0
 $ mday : int 18
 $ mon  : int 2
 $ year : int 99
 $ wday : int 4
 $ yday : int 76
 $ isdst: int 0
 - attr(*, "tzone")= chr "CET"

Note that as.Date.POSIXlt also has not time zone argument so any time
zone argument given to it is also ignored:

> as.Date.POSIXlt
function (x, ...)
.Internal(POSIXlt2Date(x))
<environment: namespace:base>

Perhaps the unexpected part is that as.Date.POSIXct always converts
relative to GMT so if you want to convert relative to anything else
its best to convert to character representation in the desired time
zone and then convert that to Date.

Also if you are dealing with dates that do not have times its best not
to use POSIXt in the first place.  Date class is a better fit.

See relevant article in R News 4/1.


On Sun, Dec 20, 2009 at 12:18 PM, MAL <diverses at univecom.ch> wrote:
> All!
>
> This piece of code:
>
> zzz1 <- as.POSIXct("1999-03-18", tz="CET")
> zzz2 <- as.POSIXlt("1999-03-18", tz="CET")
> zzz1 == zzz2
> as.Date(zzz1)
> as.Date(zzz2)
>
> yields TRUE for "zzz1==zzz2", but the two dates returned by as.Date are
> different:
>
>> as.Date(zzz1)
>
> [1] "1999-03-17"
>>
>> as.Date(zzz2)
>
> [1] "1999-03-18"
>
> I'm using R 2.10.0.
>
> Would be glad for any clarifications. Thanks!
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list