r - 在R中的1列中格式化多个日期
问题描述
我有一个从 Excel 读入 R 的日期列,其格式为以下日期格式:例如“6/12/2019 12:00:00 AM”和“43716”。
我想将此列转换为数字格式 MM/DD/YYYY。我怎样才能做到这一点?
谢谢!
解决方案
一种方法是分别处理这两种格式
#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"))
推荐阅读
- angular - 在 Firestore 中设置使用 Angular 更新的新 displayName
- java - spring-boot2 上的 Resilience4j - 断路器未打开
- html - 如何使用 marquee 标签在网站周围创建动画边框?
- linux - linux下多个USB声卡
- python - Webscraping:如何在 Python 中解析这种内容?
- javascript - npm build 如何知道要代理的 url - 该指令存储在哪里?
- spring-boot - Spring Data JDBC 使用 Boot 2.3.0 生成错误的 HSQLDB 查询
- python - 如何将列表和字典转换为字节?
- java - android studio app的Openfire MAC问题集java_home
- r - 根据 R 中其他的值在数据框中插入零