Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

r - Change timezone in a POSIXct object

Playing with dateTimes and timezone can be tricky in R. Here is my question: I want to change the time-zone on a POSIXct object

R) data <- data.frame(x=c(1,2),dateTime=as.POSIXct(c("2010-03-11 03:30:00.432","2010-03-15 03:30:00.432"),format="%Y-%m-%d %H:%M:%S",tz="America/Montreal"))
R) data
  x            dateTime
1 1 2010-03-11 03:30:00
2 2 2010-03-15 03:30:00
R) str(data)
'data.frame':   2 obs. of  2 variables:
 $ x       : num  1 2
 $ dateTime: POSIXct, format: "2010-03-11 03:30:00" "2010-03-15 03:30:00"

But if I want to change the timezone, the only thing I found is:

R) data$dateTime2 = format(data$dateTime,tz="Europe/Paris")
R) str(data)
'data.frame':   2 obs. of  3 variables:
 $ x        : num  1 2
 $ dateTime : POSIXct, format: "2010-03-11 03:30:00" "2010-03-15 03:30:00"
 $ dateTime2: chr  "2010-03-11 09:30:00" "2010-03-15 08:30:00"

Or

R) data$dateTime2 = as.POSIXlt(data$dateTime,tz="Europe/Paris")
R) str(data)
'data.frame':   2 obs. of  3 variables:
 $ x        : num  1 2
 $ dateTime : POSIXct, format: "2010-03-11 03:30:00" "2010-03-15 03:30:00"
 $ dateTime2: POSIXlt, format: "2010-03-11 09:30:00" "2010-03-15 08:30:00"

God (or somebody on SO) knows why it doesn't work with POSIXct

R) data$dateTime2 = as.POSIXct(data$dateTime,tz="Europe/Paris")
R) str(data)
'data.frame':   2 obs. of  3 variables:
 $ x        : num  1 2
 $ dateTime : POSIXct, format: "2010-03-11 03:30:00" "2010-03-15 03:30:00"
 $ dateTime2: POSIXct, format: "2010-03-11 03:30:00" "2010-03-15 03:30:00"

Do I need to convert to character and cast back to POSIXct ?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It doesn't work with POSIXct because base::as.POSIXct.default simply returns x if it's already POSIXct. You can change the timezone via the tzone attribute:

attr(data$dateTime, "tzone") <- "Europe/Paris"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...