首页 > 解决方案 > 在R中的1列中格式化多个日期

问题描述

我有一个从 Excel 读入 R 的日期列,其格式为以下日期格式:例如“6/12/2019 12:00:00 AM”和“43716”。

我想将此列转换为数字格式 MM/DD/YYYY。我怎样才能做到这一点?

谢谢!

标签: rdateformat

解决方案


一种方法是分别处理这两种格式

#Convert date-time variables into date
df$updated_date <- as.Date(as.POSIXct(df$date_col, format = "%m/%d/%Y %I:%M:%S %p", 
                           tz = "UTC"))
#Get indices of the one which are not converted from above
inds <- is.na(df$updated_date)
#Convert the remaining ones to date
df$updated_date[inds] <- as.Date(as.numeric(as.character(df$date_col[inds])),
                                 origin = "1899-12-30")
#Comvert them to format required
df$updated_date <- format(df$updated_date, "%m/%d/%Y")

df
#  x              date_col updated_date
#1 1 6/12/2019 12:00:00 AM   06/12/2019
#2 2                 43716   09/08/2019
#3 3  6/16/2019 1:00:00 PM   06/16/2019

数据

对此样本数据进行了测试:

df <- data.frame(x = 1:3, date_col = c("6/12/2019 12:00:00 AM", "43716", 
                                       "6/16/2019 1:00:00 PM"))

推荐阅读