如何使用 as.Date() 将带有缩写月份名称的字符串转换为日期?

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

我有一个包含日期和时间的列,用“”分隔,我可以将其分成两列,称为“日期”和“时间”。现在我想从日期列中选择非空行并将该列转换为日期类型(现在它是字符类型。我使用

typeof()
检查)。我用过

mutate(DATE=as.Date(dates, format="%m/%d/%y"))

但新的 DATE 列只是

<NA>
,如图所示。

这是我的程序截图和结果供您参考。

enter image description here

结果是这样的: enter image description here

我也尝试将日期格式更改为

"%Y-%m-%d"
,但没有用。

r dataframe date dplyr data-cleaning
1个回答
0
投票

您可以使用

%b
格式字符串来缩写月份名称,如下所示:

> as.Date(x, '%d-%b-%Y')
 [1] "2023-12-14" "2023-12-28" "2024-01-11" "2024-01-25" "2024-02-08" "2024-02-22" "2024-03-07"
 [8] "2024-03-21" "2024-04-04" "2024-04-18" "2024-05-02" "2024-05-16" "2024-05-30" "2024-06-13"
[15] "2024-06-27" "2024-07-11" "2024-07-25" "2024-08-08" "2024-08-22" "2024-09-05" "2024-09-19"
[22] "2024-10-03" "2024-10-17" "2024-10-31" "2024-11-14" "2024-11-28" "2024-12-12"

数据:

x <- seq.Date(Sys.Date(), Sys.Date() +365, by='14 days') |> strftime('%d-%b-%Y') |> toupper()
© www.soinside.com 2019 - 2024. All rights reserved.