Unexpected date when converting POSIXct date-time to Date - can timezone fix it?

前端 未结 2 1620
予麋鹿
予麋鹿 2021-01-26 18:46

When I try to coerce a POSIXct date-time to a Date using as.Date, it seems to return wrong date.

I suspect it has got something to

相关标签:
2条回答
  • 2021-01-26 19:25

    Using the setup in the Note at the end we can use any of these:

    # same date as print(x) shows
    as.Date(as.character(x))
    ## [1] "2020-03-24"
    
    # use the time zone stored in x (or system time zone if that is "")
    as.Date(x, tz = attr(x, "tzone"))
    ## [1] "2020-03-24"
    
    # use system time zone
    as.Date(x, tz = "")
    ## [1] "2020-03-24"
    
    # use system time zone
    as.Date(x, tz = Sys.timezone())
    ## [1] "2020-03-24"
    
    # use indicated time zone
    as.Date(x, tz = "Asia/Calcutta")
    ## [1] "2020-03-24"
    

    Note

    We have assumed this setup.

    Sys.setenv(TZ = "Asia/Calcutta")
    x <- structure(1584988320, class = c("POSIXct", "POSIXt"), tzone = "")
    
    R.version.string
    ## [1] "R version 4.0.2 Patched (2020-06-24 r78745)"
    
    0 讨论(0)
  • 2021-01-26 19:31

    The clue is in the warning message. as.Date() doesn't know how to interpret IST as a timezone and so defaults to UTC. Assuming that IST is Indian Standard Time (rather than Irish Standard time) and that IST is UTC+5:30, as.Date() is giving the expected result, even if it is incorrect for your purposes.

    Providing a date with a timezone expressed as an offset from UTC gives the desired result.

    as.Date("2020-03-24 00:02:00 UTC+5:30")
    [1] "2020-03-24"
    
    0 讨论(0)
提交回复
热议问题