How do you convert dates/times from one time zone to another in R?

后端 未结 4 2155
南旧
南旧 2020-11-27 13:27

If I have a date like this in London time: \"2009-06-03 19:30\", how can I convert it to the equivalent time in the US West Coast?

相关标签:
4条回答
  • 2020-11-27 13:46

    Package lubridate holds two functions to convert timezones. According to the help pages:


    force_tz returns a date-time that has the same clock time as x in the new time zone.

    force_tz(time, tzone = "America/Los_Angeles")
    


    with_tz changes the time zone in which an instant is displayed. The clock time displayed for the instant changes, but the moment of time described remains the same.

    with_tz(time, tzone = "America/Los_Angeles")
    
    0 讨论(0)
  • 2020-11-27 13:55

    If you'd like to do this in one line, recall that any POSIXct object in R is really just a number (seconds UTC since epoch beginning), and that the "timezone" is just an attribute that determines how that number is printed.

    Therefore, we can use the .POSIXct helper function as follows:

    x = as.POSIXct("2009-06-03 19:30", tz = "Europe/London")
    .POSIXct(as.integer(x), tz = 'America/Los_Angeles')
    # [1] "2009-06-03 11:30:00 PDT"
    

    as.integer strips the class and attributes of x, and .POSIXct is shorthand for constructing a POSIXct object; if your object has milliseconds and you'd like to keep track of them, you can use as.numeric(x).

    0 讨论(0)
  • 2020-11-27 13:58

    Change the tzone attribute of a 'POSIXct' object:

    > pb.txt <- "2009-06-03 19:30"  
    > pb.date <- as.POSIXct(pb.txt, tz="Europe/London")  
    > attributes(pb.date)$tzone <- "America/Los_Angeles"  
    > pb.date  
    [1] "2009-06-03 11:30:00 PDT"
    

    Note that this is still a POSIXct object, tzone has changed, and correct offset has been applied:

    > attributes(pb.date)
    $class
    [1] "POSIXct" "POSIXt" 
    
    $tzone
    [1] "America/Los_Angeles"
    
    0 讨论(0)
  • 2020-11-27 14:06

    First, convert the London time to a POSIXct object:

    pb.txt <- "2009-06-03 19:30"
    pb.date <- as.POSIXct(pb.txt, tz="Europe/London")
    

    Then use format to print the date in another time zone:

    > format(pb.date, tz="America/Los_Angeles",usetz=TRUE)
    [1] "2009-06-03 11:30:00 PDT"
    

    There are some tricks to finding the right time zone identifier to use. More details in this post at the Revolutions blog: Converting time zones in R: tips, tricks and pitfalls

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