r - 使用 lubridate 进行矢量化时区转换

标签 r date datetime tidyverse lubridate

我有一个包含日期时间字符串列的数据框:

library(tidyverse)
library(lubridate)

testdf = data_frame(
  mytz = c('Australia/Sydney', 'Australia/Adelaide', 'Australia/Perth'),
  mydt = c('2018-01-17T09:15:00', '2018-01-17T09:16:00', '2018-01-17T09:18:00'))

testdf

#  A tibble: 3 x 2
#   mytz               mydt
#   <chr>              <chr>
# 1 Australia/Sydney   2018-01-17T09:15:00
# 2 Australia/Adelaide 2018-01-17T09:16:00
# 3 Australia/Perth    2018-01-17T09:18:00

我想将这些日期时间字符串转换为具有各自时区的 POSIX 日期时间对象:
testdf %>% mutate(mydt_new = ymd_hms(mydt, tz = mytz))

Error in mutate_impl(.data, dots) : Evaluation error: tz argument must be a single character string. In addition: Warning message: In if (tz != "UTC") { : the condition has length > 1 and only the first element will be used



如果我使用 ymd_hms,我会得到相同的结果没有时区并将其通过管道输入 force_tz .就时区操作而言,lubridate 不支持任何类型的矢量化的结论是否公平?

最佳答案

另一种选择是 map2 .存储不同的可能更好tz输出 list因为这可能会被强制为单个 tz

library(tidyverse)
out <- testdf %>%
         mutate(mydt_new = map2(mydt, mytz, ~ymd_hms(.x, tz = .y)))

如果需要,可以是 unnest编辑
out %>%
   unnest
list 中的值是
out %>%
   pull(mydt_new)
#[[1]]
#[1] "2018-01-17 09:15:00 AEDT"

#[[2]]
#[1] "2018-01-17 09:16:00 ACDT"

#[[3]]
#[1] "2018-01-17 09:18:00 AWST"

关于r - 使用 lubridate 进行矢量化时区转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48291932/

相关文章:

javascript - 如何在 JavaScript 中将月份添加到给定日期中?

sql-server - 一台计算机上 SQL 中的日期转换错误,但代码在另一台计算机上有效?

php - fatal error :未捕获异常 ‘Exception’,消息为“DateTime::__construct():

java - 如何将日期字符串转换为joda日期时间?

mysql - 如何使用 SQL 创建以 "select"开头且不使用默认表的日期序列?

php - 将 PHP 日期时间字符串转换为 MySQL 日期时间

R 函数生成不正确的结果

使用 SparkR 替换列中的特殊字符

r - 在 R 中求解 BesselJ (J0) 函数

r - 将表达式传递给 data.table 中的嵌套分组