Why does xts shift a date one day back when creating an xts object from a data frame when TZ is not specified?

后端 未结 1 574
轻奢々
轻奢々 2021-01-20 10:20

Let me start by saying that I took a look at ?xts, realised that this is a timezone related problem and seem to have resolved it, but I don\'t understand wh

相关标签:
1条回答
  • 2021-01-20 10:56

    I do not know, and I cannot exactly reproduce your problem, but I believe it has to do with the Dates being coerced to POSIXct and back.

    This line is in the code for the xts function:

    if (inherits(order.by, "Date") && !missing(tzone)) 
        order.by <- .POSIXct(unclass(order.by) * 86400, tz = tzone)
    

    In your first call, tzone is missing, so this code is not executed. In your second call, tzone is not missing, so it is executed.

    If you step through the code in xts.R, you can see that (if tzone is missing) the Dates in aa$Date are coerced to POSIXct.

    index <- as.numeric(as.POSIXct(order.by))
    

    I think the issue is that as.Date.POSIXct has a default of tz="UTC", so that is used unless you specify a different one.

    x <- structure(1290125760, 
                   tzone = structure("America/Chicago", .Names = "TZ"), 
                   tclass = c("POSIXt", "POSIXct"), 
                   class = c("POSIXct", "POSIXt"))
    x
    #[1] "2010-11-18 18:16:00 CST"
    str(x)
    #POSIXct[1:1], format: "2010-11-18 18:16:00"
    as.Date(x)
    #[1] "2010-11-19"
    as.Date(x, origin=as.Date("1970-01-01"), tz="America/Chicago")
    #[1] "2010-11-18"
    
    0 讨论(0)
提交回复
热议问题