我在不同地点的UTC和当地时间之间的偏移时间如下(+/-HH:MM):
> x
# [1] "+00:00" "+00:00" "-03:00" "+01:00" "+03:00" "+03:00" "+00:00" "+01:00"
# [9] "+00:00" "+00:00" "+02:00" "+01:00" "+02:00" "-02:00" "+00:00" "+01:00"
我如何将其转换为时间间隔,然后使用它来使用上面的数字移动Sys.Date()
?
使用as.difftime
的另一个解决方案(有一点体操要做,因为它不识别签名字符输入):
x <- c("+00:00","+00:00","-03:00","+01:00","+03:00","+03:00","+00:00","+01:00","+00:00","+00:00","+02:00","+01:00","+02:00","-02:00","+00:00","+01:00")
as.difftime(gsub("[+-]","",x), format ="%H:%M") * ifelse(grepl("^-",x),-1,1)
#Time differences in secs
# [1] 0 0 -10800 3600 10800 10800 0 3600 0 0 7200 3600 7200 -7200 0 3600
#attr(,"tzone")
#[1] ""
所以要从Sys.time()
转移,只需:
Sys.time()+as.difftime(gsub("[+-]","",x),format ="%H:%M") * ifelse(grepl("^-",x),-1,1)
#[1] "2015-07-10 10:36:32 CEST" "2015-07-10 10:36:32 CEST" "2015-07-10 07:36:32 CEST" "2015-07-10 11:36:32 CEST" "2015-07-10 13:36:32 CEST" "2015-07-10 13:36:32 CEST" "2015-07-10 10:36:32 CEST"
#[8] "2015-07-10 11:36:32 CEST" "2015-07-10 10:36:32 CEST" "2015-07-10 10:36:32 CEST" "2015-07-10 12:36:32 CEST" "2015-07-10 11:36:32 CEST" "2015-07-10 12:36:32 CEST" "2015-07-10 08:36:32 CEST"
#[15] "2015-07-10 10:36:32 CEST" "2015-07-10 11:36:32 CEST"
如果你的输入是数字,它会更直接,因为它可以识别有符号的数字输入:
y <- c(-1,2,3,0,-4,-6.5)
Sys.time() + as.difftime(y, units="hours")
# [1] "2015-07-10 09:39:31 CEST" "2015-07-10 12:39:31 CEST" "2015-07-10 13:39:31 CEST" "2015-07-10 10:39:31 CEST" "2015-07-10 06:39:31 CEST" "2015-07-10 04:09:31 CEST"
这里我有一个(笨拙的)解决方案,但我认为它有效。等待更优雅的解决方案。步骤是,gsub
将所有标点符号和+
符号串起来。将它们全部转换为数字,除以100以得到,例如-200为-2,并将它们全部作为hours
函数的参数传递。
library(lubridate)
x1 <- gsub("[:punct:]|\+", "", x)
x1 <- as.numeric(as.character(x1))
x1 <- x1 / 100
Sys.Date() + hours(x1)
[1] "2015-07-09 00:00:00 UTC" "2015-07-09 00:00:00 UTC"
[3] "2015-07-08 21:00:00 UTC" "2015-07-09 01:00:00 UTC"
[5] "2015-07-09 03:00:00 UTC" "2015-07-09 03:00:00 UTC"
[7] "2015-07-09 00:00:00 UTC" "2015-07-09 01:00:00 UTC"
[9] "2015-07-09 00:00:00 UTC" "2015-07-09 00:00:00 UTC"
[11] "2015-07-09 02:00:00 UTC" "2015-07-09 01:00:00 UTC"
[13] "2015-07-09 02:00:00 UTC" "2015-07-08 22:00:00 UTC"
[15] "2015-07-09 00:00:00 UTC" "2015-07-09 01:00:00 UTC"
使用过的数据:
x <- c("+00:00", "+00:00", "-03:00", "+01:00", "+03:00", "+03:00", "+00:00", "+01:00",
"+00:00", "+00:00", "+02:00", "+01:00", "+02:00", "-02:00", "+00:00", "+01:00")
编辑:分钟解决方案
这里使用的数据是向量y
,也包含分钟。
y <- c("+03:30", "+02:45", "-03:50", "-05:00")
y1 <- unlist(strsplit(y, "[:punct:]"))
y1 <- gsub("\+", "", y1)
y1 <- as.numeric(as.character(y1))
MinuteS <- y1[1:length(y1) %% 2 == 0]
HourS <- y1[1:length(y1) %% 2 == 1]
Sys.Date() + minutes(MinuteS) + hours(HourS)
[1] "2015-07-09 03:30:00 UTC"
[2] "2015-07-09 02:45:00 UTC"
[3] "2015-07-08 21:50:00 UTC"
[4] "2015-07-08 19:00:00 UTC"