简体   繁体   English

R 从多种格式转换为日期

[英]R Convert to date from multiple formats

I need to convert a string of dates that is in multiple formats to valid dates.我需要将具有多种格式的日期字符串转换为有效日期。

eg例如

dates <- c("01-01-2017","02-01-2017","12-01-2016","20160901","20161001", "20161101")

> as.Date(dates, format=c("%m-%d-%Y","%Y%m%d"))
[1] "2017-01-01" NA           "2016-12-01" "2016-09-01" NA           "2016-11-01"

two dates show as NA两个日期显示为 NA

This is pretty much I wrote the anytime package for:这几乎是我为以下目的编写的任何时间包:

R> dates <- c("01-01-2017","02-01-2017","12-01-2016","20160901","20161001", 
+             "20161101")
R> library(anytime)
R> anydate(dates)
[1] "2017-01-01" "2017-02-01" "2016-12-01" "2016-09-01" 
[5] "2016-10-01" "2016-11-01"
R> 

Parse any sane input reliably and without explicit format or origin or other line noise.可靠地解析任何理智的输入,没有明确的格式来源或其他线路噪音。

That being said, not starting ISO style with the year is asking for potential trouble, so 02-03-2017 could be February 3 or March 2. I am following the North American convention I too consider somewhat broken -- but is so darn prevalent.话虽这么说,没有开始与去年ISO风格寻求潜在的麻烦,所以02-03-2017可能是2月3日或3月2日我下面北美约定我也考虑有些破-但这么混账的流行. Do yourself a favour and try to limit inputs to ISO dates, at least ISO order YYYYMMDD.帮自己一个忙,并尝试将输入限制为 ISO 日期,至少 ISO 订单为 YYYYMMDD。

I have tried library(anytime), however for big data did not work.我尝试过图书馆(任何时候),但是对于大数据不起作用。 Then, I found useful this sequence:然后,我发现这个序列很有用:

df$Date2 <- format(as.Date(df$Date, format="%m/%d/%Y"), "%d/%m/%y")

df$Date2 <- as.Date(df$Date2,"%d/%m/%y")

It worked for me to "8/10/2005" as well as "08/13/05" in the same column.它对我在同一列中的“8/10/2005”以及“08/13/05”都有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM