Tidyverse 解析日期字符串

Tidyverse Parse Date String

我在日期后有 space 的数据框中有一个 "date" 列。我想 FIND space,然后 LEFT 到该位置减去 1 个位置,并将该字符串转换为日期。这是一个代表性的例子:

library(tidyverse)
library(lubridate)

my_sales <- c(10, 15, 20, 15)
my_dates <- c("12/30/02 0:00", "1/4/03 0:00", "1/11/03 0:00", "1/19/03 0:00")
df <- data.frame(my_sales, my_dates)
df$my_dates <- as.character(df$my_dates)

df$my_dates_temp1 <- str_sub(df$my_dates, 1, str_locate(df$my_dates, ' ')[, 1]-1)
head(df)

>   my_sales      my_dates my_dates_temp1
> 1       10 12/30/02 0:00       12/30/02
> 2       15   1/4/03 0:00         1/4/03
> 3       20  1/11/03 0:00        1/11/03
> 4       15  1/19/03 0:00        1/19/03

我的问题是当我尝试将 my_dates_temp1 转换为日期时。

基础 R

as.Date(df$my_dates_temp1)
> Error in charToDate(x) : 
>   character string is not in a standard unambiguous format

润滑

lubridate::as_date(df$my_dates_temp1)
> [1] NA NA NA NA
> Warning message:
> All formats failed to parse. No formats found. 

这怎么不是可以转换为日期的格式,我该如何转换呢?

我们需要 format,因为它不是 "YYYY-MM-DD"

的默认格式
as.Date(df$my_dates_temp1, "%m/%d/%y")
#[1] "2002-12-30" "2003-01-04" "2003-01-11" "2003-01-19"

或使用

lubridate::mdy(df$my_dates_temp1)
#[1] "2002-12-30" "2003-01-04" "2003-01-11" "2003-01-19"