如何将日期时间+时区字符串转换为具有 tzone 属性的 POSIXct/POSIXt?

问题描述 投票:0回答:1

使用

{lubridate}
包将日期时间+时区从 character 转换为 POSIXct/POSIXt 同时将时区保留到
tzone
属性中的“规范”方式是什么?

示例

我得到了

my_time_string

my_time_string <- "2023-02-01 19:16:24 UTC"
class(my_time_string)
#> [1] "character"
attributes(my_time_string)
#> NULL

我想将其转换为

my_time_dttm
:

my_time_dttm <- lubridate::ymd_hms("2023-02-01 19:16:24", tz = "UTC")
class(my_time_dttm)
#> [1] "POSIXct" "POSIXt"
attributes(my_time_dttm)
#> $class
#> [1] "POSIXct" "POSIXt" 
#> 
#> $tzone
#> [1] "UTC"

是否有开箱即用的函数/方法,或者我必须先对原始函数/方法进行子串以提取时区?

r string datetime timezone lubridate
1个回答
1
投票

您可以将这些日期时间存储在列表结构中:

c(
"2023-02-01 19:16:24 UTC",
"2023-02-02 19:16:24 GMT") %>% 
  as.list %>% 
  lapply(\(x) lubridate::ymd_hms(x, tz=str_extract(x, "\\b[:alpha:]+\\z"))) # or other regex if required

这将导致:

[[1]]
[1] "2023-02-01 19:16:24 UTC"

[[2]]
[1] "2023-02-02 19:16:24 GMT"

具有以下结构:

List of 2
 $ : POSIXct[1:1], format: "2023-02-01 19:16:24"
 $ : POSIXct[1:1], format: "2023-02-02 19:16:24"

毕竟,您可以将所有日期转换为单个 tz,例如添加另一行:

... %>% 
  lapply(\(x) lubridate::force_tz(x, tz="UTC"))

这会给你:

[[1]]
[1] "2023-02-01 19:16:24 UTC"

[[2]]
[1] "2023-02-02 19:16:24 UTC"
© www.soinside.com 2019 - 2024. All rights reserved.