【问题标题】:Format Multiple Date in 1 Column in R在R中的1列中格式化多个日期
【发布时间】:2020-03-23 15:20:55
【问题描述】:

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

我想将此列转换为数字格式 MM/DD/YYYY。我该怎么做?

谢谢!

【问题讨论】:

标签: r date format


【解决方案1】:

我会推荐

read.csv(file.csv,colClasses="character") #or whatever read function you're using

这将确保字符串从原始文件正确转换为 R。

然后我将使用 lubridate 包中的mdy(),字符串将作为日期对象读入。

【讨论】:

  • 我强烈建议不要这样做。这会将 所有 列转换为 character 向量,这将要求您手动将任何包含数字的列转换回 numericinteger
【解决方案2】:

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

#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"))

【讨论】:

    猜你喜欢
    • 2021-09-14
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    相关资源
    最近更新 更多