[R] Fwd: strptime() problem?

Whit Armstrong Whit.Armstrong at tudor.com
Tue Aug 17 18:14:37 CEST 2004


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
[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
> print.POSIXct
function (x, ...) 
    print(format(x, usetz = TRUE, ...), ...)
<environment: namespace:base>

So, that function is just calling "format" which gets dispatched to

> 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.


> 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

> get("[.POSIXct")
function (x, ..., drop = TRUE) 
    cl <- oldClass(x)
    class(x) <- NULL
    val <- NextMethod("[")
    class(val) <- cl
<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

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
[1] "GMT"

I think that should straighten out your problem.

Hope that helps,

More information about the R-help mailing list