我有一个日期的字符向量,我想将其转换为不同的时区。
pubdate
[1] "Fri, 10 Jul 2015 03:21:23 +0000" "Fri, 10 Jul 2015 03:04:55 +0000"
[3] "Thu, 09 Jul 2015 23:49:01 +0000" "Thu, 09 Jul 2015 23:30:37 +0000"
[5] "Thu, 09 Jul 2015 23:27:44 +0000" "Thu, 09 Jul 2015 23:16:46 +0000"
[7] "Thu, 09 Jul 2015 23:14:06 +0000" "Thu, 09 Jul 2015 23:10:20 +0000"
[9] "Thu, 09 Jul 2015 23:07:52 +0000" "Thu, 09 Jul 2015 22:37:41 +0000"
[11] "Thu, 09 Jul 2015 22:35:06 +0000"
我为此创建了一个函数。
temp <- as.matrix(0)
for (i in 1:length(pubdate)){
tmp_dta <- strptime(pubdate[[i]],format="%a, %d %b %Y %H:%M:%S", tz="GMT")
tmp_dta$hour <- tmp_dta$hour - 1
tmp_dta <- as.POSIXct(tmp_dta)
attributes(tmp_dta)$tzone <- "Asia/Manila"
temp[i] <- tmp_dta
}
然而,当我试图打印临时数据时,它似乎返回了秒数。这里
> temp
[1] 1436494883 1436493895 1436482141 1436481037 1436480864 1436480206 1436480046 1436479820
[9] 1436479672 1436477861 1436477706
我可以知道如何更改它作为日期返回吗?例如:&#34; 2015-07-10 10:21:23 PHT&#34;
谢谢!
更新:正如Nicola在下面所建议的那样,我删除了循环并添加了他建议的代码。下面的代码有效:
tmp_dta <- strptime(pubdate,format="%a, %d %b %Y %H:%M:%S", tz="GMT")
x <- as.POSIXct(tmp_dta)
attributes(x)$tzone <- "Asia/Manila"
newpubdate <- x - 3600
答案 0 :(得分:0)
您可以在一行中完成整个操作:
pubdate <- c( "Fri, 10 Jul 2015 03:21:23 +0000" ,"Fri, 10 Jul 2015 03:04:55 +0000","Thu, 09 Jul 2015 23:49:01 +0000", "Thu, 09 Jul 2015 23:30:37 +0000","Thu, 09 Jul 2015 23:27:44 +0000", "Thu, 09 Jul 2015 23:16:46 +0000","Thu, 09 Jul 2015 23:14:06 +0000","Thu, 09 Jul 2015 23:10:20 +0000", "Thu, 09 Jul 2015 23:07:52 +0000", "Thu, 09 Jul 2015 22:37:41 +0000","Thu, 09 Jul 2015 22:35:06 +0000")
strptime(pubdate,"%a, %d %b %Y %H:%M:%S %z",tz="Asia/Manila")
# [1] "2015-07-10 11:21:23 PHT" "2015-07-10 11:04:55 PHT" "2015-07-10 07:49:01 PHT" "2015-07-10 07:30:37 PHT" "2015-07-10 07:27:44 PHT" "2015-07-10 07:16:46 PHT" "2015-07-10 07:14:06 PHT" "2015-07-10 07:10:20 PHT"
# [9] "2015-07-10 07:07:52 PHT" "2015-07-10 06:37:41 PHT" "2015-07-10 06:35:06 PHT"
如果您认为存在一小时的差异(我不认为有:您是否考虑过夏令时?),那么,正如@nicola建议的那样:
strptime(pubdate,"%a, %d %b %Y %H:%M:%S %z",tz="Asia/Manila") - as.difftime(1,unit="hours")
# [1] "2015-07-10 10:21:23 PHT" "2015-07-10 10:04:55 PHT" "2015-07-10 06:49:01 PHT" "2015-07-10 06:30:37 PHT" "2015-07-10 06:27:44 PHT" "2015-07-10 06:16:46 PHT" "2015-07-10 06:14:06 PHT" "2015-07-10 06:10:20 PHT"
# [9] "2015-07-10 06:07:52 PHT" "2015-07-10 05:37:41 PHT" "2015-07-10 05:35:06 PHT"