[R] Fwd: strptime() problem?
Whit Armstrong
Whit.Armstrong at tudor.com
Tue Aug 17 18:14:37 CEST 2004
Javier,
I recently had a problem with dates. This example might shed some light on
your problem.
> x <- ISOdate(rep(2000,2),rep(3,2),rep(26,2),hour=0)
> x
[1] "2000-03-26 GMT" "2000-03-26 GMT"
> unclass(x)
[1] 954028800 954028800
attr(,"tzone")
[1] "GMT"
When one creates a date with ISOdate, the resulting object is of class
POSIXct and is given the attribute "tzone" which is set to "GMT."
When one prints an object of class POSIXct the function "print.POSIXct" is
called:
> print.POSIXct
function (x, ...)
{
print(format(x, usetz = TRUE, ...), ...)
invisible(x)
}
<environment: namespace:base>
>
So, that function is just calling "format" which gets dispatched to
"format.POSIXct":
> format.POSIXct
function (x, format = "", tz = "", usetz = FALSE, ...)
{
if (!inherits(x, "POSIXct"))
stop("wrong class")
if (missing(tz) && !is.null(tzone <- attr(x, "tzone")))
tz <- tzone
structure(format.POSIXlt(as.POSIXlt(x, tz), format, usetz,
...), names = names(x))
}
<environment: namespace:base>
>
Now, if one looks carefully at this code, you will see that it tests for the
attribute "tzone" on the object that is passed in. If it finds that
attribute, then it is passed on to "format.POSIXlt" (which is the function
that ultimately does the printing). If there is no "tzone" attribute, then
"" is passed to "format.POSIXlt" as the tzone, which causes the object to be
printed in your locale specific format.
See:
> attr(x,"tzone") <- ""
> x
[1] "2000-03-25 19:00:00 Eastern Standard Time" "2000-03-25 19:00:00 Eastern
Standard Time"
> attr(x,"tzone") <- "GMT"
> x
[1] "2000-03-26 GMT" "2000-03-26 GMT"
>
Now this is the part that really got me confused:
> x
[1] "2000-03-26 GMT" "2000-03-26 GMT"
> x[1]
[1] "2000-03-25 19:00:00 Eastern Standard Time"
>
What happens in the above case is that the code for "[.POSIXct" looks like
this:
> get("[.POSIXct")
function (x, ..., drop = TRUE)
{
cl <- oldClass(x)
class(x) <- NULL
val <- NextMethod("[")
class(val) <- cl
val
}
<environment: namespace:base>
>
The attribute "tzone" is not preserved!! when "val" is created from the
call to NextMethod, its class is restored, but not its "tzone" attribute.
So any dates of class POSIXct that are printed after they have been
subscripted ("[") will have their "tzone" attribute stripped, and will print
in the local specific format.
For your specific case, I would convert all my dates to POSIXct, then set
the attribute "tzone" to "GMT." After that, be very careful when
subscripting them, or you will find them printing in local specific formats
again.
for you:
> y <- strptime("4/3/2000",format="%m/%d/%Y")
> y
[1] "2000-04-03"
> y <- as.POSIXct(y,"GMT")
> y
[1] "2000-04-03 GMT"
> unclass(y)
[1] 954720000
attr(,"tzone")
[1] "GMT"
>
I think that should straighten out your problem.
Hope that helps,
Whit
More information about the R-help
mailing list