Date conversion from POSIXct to Date in R

前端 未结 3 745
野性不改
野性不改 2020-11-27 04:39

can anyone tell me why R give such outcome below:

> as.POSIXct(\"2013-01-01 08:00\")
[1] \"2013-01-01 08:00:00 HKT\"
> as.Date(as.POSIXct(\"2013-01-01          


        
相关标签:
3条回答
  • 2020-11-27 04:49

    This happens as documented and previously explained when contemporaneous UTC time is before (your third example) or after midnight on your POSIXct date. To see the math for yourself, inspect as.Date.POSIXct at the console. The math under the default tz="UTC" is clear. In the non-default case, R essentially calls as.Date.POSIXlt, and the date-travel does not occur. In fact, if you had started with the lt object you would not have had this problem:

    > as.Date(as.POSIXlt("2013-01-01 07:00", tz = "Hongkong"))  
    [1] "2013-01-01"
    

    The easiest work-around is to call as.Date with tz="" to force using the less offending as.Date.POSIXlt algorithm:

    > as.Date(as.POSIXct("2013-01-01 07:00"), tz = "")  
    [1] "2013-01-01"
    
    0 讨论(0)
  • 2020-11-27 04:51

    Use the time zone parameter of as.Date:

    as.Date(as.POSIXct("2013-01-01 07:00",tz="Hongkong"))
    #[1] "2012-12-31"
    
    as.Date(as.POSIXct("2013-01-01 07:00",tz="Hongkong"),tz="Hongkong")
    #[1] "2013-01-01"
    

    In fact, I recommend always using the tz parameter when using date-time converting functions. There are other nasty surprises, e.g. with daylight saving time.

    0 讨论(0)
  • 2020-11-27 04:52

    The problem here is timezones - you can see you're in "HKT". Try:

    as.Date(as.POSIXct("2013-01-01 07:00", 'GMT'))
    [1] "2013-01-01"
    

    From ?as.Date():

    ["POSIXct" is] converted to days by ignoring the time after midnight in the representation of the time in specified timezone, default UTC

    0 讨论(0)
提交回复
热议问题