解析不同数量的时间符号中的时间

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

我有一个日期和时间向量

tm <- c("20231130 162900", "20231009 75400", "20240216 3100", "20230725 0")

我将其转换为时间格式

library(tidyverse)
strsplit(tm, " ") |>
  map_chr(\(x)  paste(x[1], stringr::str_pad(x[2], 6, "left", "0"))) |>
  lubridate::ymd_hms()

结果

[1] "2023-11-30 16:29:00 UTC" "2023-10-09 07:54:00 UTC" "2024-02-16 00:31:00 UTC" "2023-07-25 00:00:00 UTC"

有哪些更短、更易读的选项来进行此转换?

r
1个回答
0
投票

不确定可读性,但您可以将填充操作作为函数传递给

str_replace()
并跳过分割和映射:

library(stringr)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
tm <- c("20231130 162900", "20231009 75400", "20240216 3100", "20230725 0")
tm |> 
  str_replace("\\d+$", \(time_) str_pad(time_, 6, "left", "0")) |> 
  ymd_hms()
#> [1] "2023-11-30 16:29:00 UTC" "2023-10-09 07:54:00 UTC"
#> [3] "2024-02-16 00:31:00 UTC" "2023-07-25 00:00:00 UTC"

创建于 2024-04-25,使用 reprex v2.1.0

© www.soinside.com 2019 - 2024. All rights reserved.