尝试反向转换时区向量

我有这个时间戳数据库(AlertTime),我知道它们在哪个时区(TimeZone)。我知道如何将这些日期设置为POSIXCT或全部为UTC,但是由于大多数功能都不接受tz的矢量,因此我很难将它们标识为本地时间戳。

我确实需要正确设置本地时间戳(AlertTimeLocal)和等效UTC(AlertTimeUTC)。

AlertTime               TimeZone                AlertTimeLocal (desired)  AlertTimeUTC (desired)
11 May 2020, 06:22 PM   America/Denver          2020-05-11 18:22:00 MDT   2020-05-12 00:22:00 MDT
11 MAY 2020, 04:11 AM   America/Los_Angeles     2020-05-11 04:11:00 PDT   2020-05-11 11:11:00 UTC
10 MAY 2020, 03:38 PM   America/Chicago         2020-05-10 15:38:00 CDT   2020-05-10 20:38:00 CDT

我正在使用此代码,但似乎不再执行任何操作:

FreshAir$AlertTimeLocal <- mapply(function(x,y) {format(x, tz=y, usetz=TRUE)}, FreshAir$AlertTime, FreshAir$TimeZone)

一个棘手的解决方案是将所有RAW时间戳设置为UTC,然后将它们转换为另一个方向的等效时区吗?

评论
夜~太美
夜~太美

We can use force_tzs from lubridate

library(lubridate)
library(dplyr)
df1 %>%
    mutate(AlertTimeLocal = dmy_hm(AlertTime), 
           AlertTimeUTC = force_tzs(AlertTimeLocal, tzones = TimeZone))
# AlertTime            TimeZone      AlertTimeLocal        AlertTimeUTC
#1 11 May 2020, 06:22 PM      America/Denver 2020-05-11 18:22:00 2020-05-12 00:22:00
#2 11 MAY 2020, 04:11 AM America/Los_Angeles 2020-05-11 04:11:00 2020-05-11 11:11:00
#3 10 MAY 2020, 03:38 PM     America/Chicago 2020-05-10 15:38:00 2020-05-10 20:38:00

数据

df1 <- structure(list(AlertTime = c("11 May 2020, 06:22 PM",
       "11 MAY 2020, 04:11 AM", 
"10 MAY 2020, 03:38 PM"), TimeZone = c("America/Denver", 
"America/Los_Angeles", 
"America/Chicago")), class = "data.frame", row.names = c(NA, 
-3L))
点赞
评论
Lee
Lee

我认为整洁的解决方案可能看起来更干净,但是如果您想要基本的R解决方案,可以使用以下替代方法:


df1$AlertTime1 <- 
  c.POSIXct(Map(as.POSIXct, df1$AlertTime, tz = df1$TimeZone, format = "%d %b %Y, %I:%M %p"))
attr(df1$AlertTime1, "tzone") <- "UTC"
df1
#               AlertTime            TimeZone          AlertTime1
# 1 11 May 2020, 06:22 PM      America/Denver 2020-05-12 00:22:00
# 2 11 MAY 2020, 04:11 AM America/Los_Angeles 2020-05-11 11:11:00
# 3 10 MAY 2020, 03:38 PM     America/Chicago 2020-05-10 20:38:00
点赞
评论