R - UTC to LOCAL time given Olson timezones

后端 未结 2 851
不知归路
不知归路 2021-01-15 14:23

I have time series data from 1974-2013 with a column for datetimeUTC (YYYY-MM-DD hh:mm +0000), and a column for the timezones in Olson format (e.g., Canada/Pacific, Canada/E

相关标签:
2条回答
  • 2021-01-15 15:15

    If you have only two time zones to convert to and know the difference in time between UTC and those two. Using @thelatemail's dataset

    transform(dataset, 
    localtime=as.POSIXct(datetimeUTC, "%Y-%m-%d %H:%M %z")-
               c(5*3600,8*3600)[as.numeric(factor(olson))])
     #            datetimeUTC          olson           localtime
    #1 2014-01-01 00:00 +0000 Canada/Eastern 2013-12-31 19:00:00
    #2 2014-01-01 00:00 +0000 Canada/Pacific 2013-12-31 16:00:00
    
    0 讨论(0)
  • 2021-01-15 15:20

    You could format back and forth a bit to get a local time representation in a character format. E.g.:

    dataset <- data.frame(
      datetimeUTC=c("2014-01-01 00:00 +0000","2014-01-01 00:00 +0000"),
      olson=c("Canada/Eastern", "Canada/Pacific"),
      stringsAsFactors=FALSE
    )
    
    #             datetimeUTC          olson
    #1 2014-01-01 00:00 +0000 Canada/Eastern
    #2 2014-01-01 00:00 +0000 Canada/Pacific
    
    dataset$localtime <- with(dataset, 
         mapply(function(dt,ol) format(
                  as.POSIXct(dt,"%Y-%m-%d %H:%M %z",tz=ol),
                  "%Y-%m-%d %H:%M %z"), 
                  datetimeUTC, olson
                )
         )
    
    #             datetimeUTC          olson              localtime
    #1 2014-01-01 00:00 +0000 Canada/Eastern 2013-12-31 19:00 -0500
    #2 2014-01-01 00:00 +0000 Canada/Pacific 2013-12-31 16:00 -0800
    
    0 讨论(0)
提交回复
热议问题