as.Date(as.POSIXct()) gives the wrong date?

前端 未结 2 542
小鲜肉
小鲜肉 2020-12-06 16:25

I\'d been trying to look through a dataframe extracting all rows where the date component of a POSIXct column matched a certain value.I came across the following which is co

2条回答
  •  生来不讨喜
    2020-12-06 17:01

    Fellow Australian chiming in here (Brisbane location, Win7 Enterprise 64 bit, R3.0.1):

    I can replicate your issue:

    > dt <- as.POSIXct('2012-08-06 09:35:23')
    > dt
    [1] "2012-08-06 09:35:23 EST"
    > as.Date(dt)
    [1] "2012-08-05"
    

    Since as.Date defaults to UTC (GMT) as listed in ?as.Date:

    ## S3 method for class 'POSIXct'
    as.Date(x, tz = "UTC", ...) 
    

    Forcing the POSIXct representation to UTC then works as expected:

    > dt <- as.POSIXct('2012-08-06 09:35:23',tz="UTC")
    > as.Date(dt)
    [1] "2012-08-06"
    

    Alternatively, matching them both to my local tz works fine too:

    > dt <- as.POSIXct('2012-08-06 09:35:23',tz="Australia/Brisbane")
    > as.Date(dt,tz="Australia/Brisbane")
    [1] "2012-08-06"
    

    Edit: Ambiguity with the EST specification seems to be an issue for me:

    Default use of as.POSIXct

    > dt.def <- as.POSIXct("2012-01-01 22:00:00")
    > dt.def
    [1] "2012-01-01 22:00:00 EST"
    > as.numeric(dt.def)
    [1] 1325419200
    > 
    

    Ambiguous EST - should be the same as default

    > dt.est <- as.POSIXct("2012-01-01 22:00:00",tz="EST")
    > dt.est
    [1] "2012-01-01 22:00:00 EST"
    > as.numeric(dt.est)
    [1] 1325473200
    > 
    

    Unambiguous Brisbane, Australia timezone

    > dt.bris <- as.POSIXct("2012-01-01 22:00:00",tz="Australia/Brisbane")
    > dt.bris
    [1] "2012-01-01 22:00:00 EST"
    > as.numeric(dt.bris )
    [1] 1325419200
    > 
    

    Differences

    > dt.est - dt.def
    Time difference of 15 hours
    > dt.est - dt.bris
    Time difference of 15 hours
    > dt.bris - dt.def
    Time difference of 0 secs
    

提交回复
热议问题