Modifying timezone of a POSIXct object without changing the display

后端 未结 3 436
无人及你
无人及你 2021-02-01 23:45

I have a POSIXct object and would like to change it\'s tz attribute WITHOUT R to interpret it (interpret it would mean to change how the datetime is di

3条回答
  •  执笔经年
    2021-02-02 00:29

    An alternative to the lubridate package is via conversion to and back from character type:

    recastTimezone.POSIXct <- function(x, tz) return(
      as.POSIXct(as.character(x), origin = as.POSIXct("1970-01-01"), tz = tz))
    

    (Adapted from GSee's answer)

    Don't know if this is efficient, but it would work for time zones with daylight savings.

    Test code:

    x <- as.POSIXct('2003-01-03 14:00:00', tz = 'Etc/UTC')
    x
    recastTimezone.POSIXct(x, tz = 'Australia/Melbourne')
    

    Output:

    [1] "2003-01-03 14:00:00 UTC"
    [1] "2003-01-03 14:00:00 AEDT" # Nothing is changed apart from the time zone.
    

    Output if I replaced as.character() by as.numeric() (as GSee had done):

    [1] "2003-01-03 14:00:00 UTC"
    [1] "2003-01-03 15:00:00 AEDT" # An hour is added.
    

提交回复
热议问题