通过添加到POSIXlt来更改不同时区的日期

时间:2012-07-24 16:27:34

标签: r

当我尝试在我的数据集中本地化“date”(class = POSIXlt的变量)的时间时,我遇到了错误。示例代码如下:

# All dates are coded by survey software in EST(not local time)
date <- c("2011-07-26 07:23", "2011-07-29 07:34", "2011-07-29 07:40")
region <-c("USA-EST", "UK", "Singapore")

#Change the times based on time-zone differences
start_time<-strptime(date,"%Y-%m-%d %h:%m")
localtime=as.POSIXlt(start_time)
localtime<-ifelse(region=="UK",start_time+6,start_time)
localtime<-ifelse(region=="Singapore",start_time+12,start_time)

#Then, I need to extract the hour and weekday
weekday<-weekdays(localtime)
hour<-factor(localtime)

我的"ifelse"语句一定有问题,因为我收到错误:number of items to replace is not a multiple of replacement length。请帮忙!

2 个答案:

答案 0 :(得分:2)

如何使用R的本机时间码?诀窍是你不能在POSIX向量中有多个时区,所以请改用一个列表:

region <- c("EST","Europe/London","Asia/Singapore")
(localtime <- lapply(seq(date),function(x) as.POSIXlt(date[x],tz=region[x])))
[[1]]
[1] "2011-07-26 07:23:00 EST"

[[2]]
[1] "2011-07-29 07:34:00 Europe/London"

[[3]]
[1] "2011-07-29 07:40:00 Asia/Singapore"

要在单个时区内转换为矢量:

Reduce("c",localtime)
[1] "2011-07-26 13:23:00 BST" "2011-07-29 07:34:00 BST"
[3] "2011-07-29 00:40:00 BST"

请注意,我的系统时区是BST,但如果您的系统是EST,它将转换为。

答案 1 :(得分:0)

您可以使用POSIXct中内置的时区处理:

> start_time <- as.POSIXct(date,"%Y-%m-%d %H:%M", tz = "America/New_York")
> start_time
[1] "2011-07-26 07:23:00 EDT" "2011-07-29 07:34:00 EDT" "2011-07-29 07:40:00 EDT"
> format(start_time, tz="Europe/London", usetz=TRUE)
[1] "2011-07-26 12:23:00 BST" "2011-07-29 12:34:00 BST" "2011-07-29 12:40:00 BST"
> format(start_time, tz="Asia/Singapore", usetz=TRUE)
[1] "2011-07-26 19:23:00 SGT" "2011-07-29 19:34:00 SGT" "2011-07-29 19:40:00 SGT"
相关问题