我有一个数据框df,它有2列(utc时间戳和时区),我想创建一列以当地时间为基础的本地时区。我尝试了以下一些操作。
This is my dataframe
df<-data.frame(utc_time_stamp=c("2019-04-28 18:35:26","2019-04-28 21:28:58","2019-04-28 18:59:01"),time_zonne=c("Asia/Tokyo","Australia/Brisbane","Etc/GMT-12"))
#This is what I tried
df$utc_time_stamp<-as.POSIXct(df$utc_time_stamp,format="%Y-%m-%d %H:%M:%S",tz='GMT')
df$new_local_time<-format(df$utc_time_stamp,tz=df$time_zone,usetz=TRUE)
#This is the error I get
Error in as.POSIXlt.POSIXct(x, tz) : invalid 'tz' value
答案 0 :(得分:1)
您对a)因素和b)传递向量有疑问。因此,一种解决方案是将stringsAsFactors
设置为FALSE
并创建一个函数来Vectorize
输入:
df <- data.frame(..., stringsAsFactors=FALSE)
df$utc_time_stamp <- as.POSIXct(df$utc_time_stamp, format="%Y-%m-%d %H:%M:%S", tz='GMT')
tz_v <- Vectorize(function(x,y) {format(x, tz=y, usetz=TRUE)})
df$new_local_time <- tz_v(df$utc_time_stamp, df$time_zone)
df
输出:
>>> utc_time_stamp time_zone new_local_time
>>> 1 2019-04-28 18:35:26 Asia/Tokyo 2019-04-29 03:35:26 JST
>>> 2 2019-04-28 21:28:58 Australia/Brisbane 2019-04-29 07:28:58 AEST
>>> 3 2019-04-28 18:59:01 Etc/GMT-12 2019-04-29 06:59:01 +12