R - UTC to LOCAL time given Olson timezones

独自空忆成欢 提交于 2019-12-01 10:35:16

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!