lubridate的向量化时区转换 [英] Vectorised time zone conversion with lubridate

查看:79
本文介绍了lubridate的向量化时区转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a data frame with a column of date-time strings:

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日期时间对象:

I want to convert these date-time strings to POSIX date-time objects with their respective timezones:

testdf %>% mutate(mydt_new = ymd_hms(mydt, tz = mytz))

mutate_impl(.data,点)中的错误: 评估错误:tz参数必须是单个字符串. 另外:警告消息: 在if(tz!="UTC"){: 条件的长度> 1,并且只会使用第一个元素

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不支持任何形式的矢量化是否公平?

I get the same result if I use ymd_hms without a timezone and pipe it into force_tz. Is it fair to conclude that lubridate doesn't support any sort of vectorisation when it comes to timezone operations?

推荐答案

另一个选项是map2.最好将不同的tz输出存储在list中,因为这可能被强制为单个tz

Another option is map2. It may be better to store different tz output in a list as this may get coerced to a single 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"

这篇关于lubridate的向量化时区转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆