我在不同位置的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()
?
答案 0 :(得分:1)
这里我有一个(笨拙的)解决方案,但我认为它有效。等待更优雅的解决方案。步骤为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"
答案 1 :(得分:1)
使用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"