没有分隔符的python熊猫解析日期的时间数据“060116”不匹配格式“%dd%mm%YY”(匹配)

时间:2022-09-30 02:26:51

I am trying to parse a date column that looks like the one below,

我正在解析一个日期列它看起来像下面这个,

date
061116
061216
061316
061416

However I cannot get pandas to accept the date format as there is no delimiter (eg '/'). I have tried this below but receive the error:

但是我不能让熊猫接受日期格式,因为没有分隔符(如'/')。我试过以下的方法,但是收到错误信息:

ValueError: time data '060116' does not match format '%dd%mm%YY' (match)

ValueError:时间数据“060116”不匹配格式“%dd%mm%YY”(匹配)

pd.to_datetime(df['Date'], format='%dd%mm%YY')

2 个解决方案

#1


2  

You need add parameter errors='coerce' to_datetime, because 13 and 14 months does not exist, so this dates are converted to NaT:

您需要添加参数错误='强制' to_datetime,因为13和14个月不存在,所以这个日期被转换为NaT:

print (pd.to_datetime(df['Date'], format='%d%m%y', errors='coerce'))
0   2016-11-06
1   2016-12-06
2          NaT
3          NaT
Name: Date, dtype: datetime64[ns]

Or maybe you need swap months with days:

或者你需要用几天来交换:

print (pd.to_datetime(df['Date'], format='%m%d%y'))

0   2016-06-11
1   2016-06-12
2   2016-06-13
3   2016-06-14
Name: Date, dtype: datetime64[ns]

EDIT:

编辑:

print (df)
         Date
0  0611160130
1  0612160130
2  0613160130
3  0614160130

print (pd.to_datetime(df['Date'], format='%m%d%y%H%M', errors='coerce'))
0   2016-06-11 01:30:00
1   2016-06-12 01:30:00
2   2016-06-13 01:30:00
3   2016-06-14 01:30:00
Name: Date, dtype: datetime64[ns]

Python's strftime directives.

Python的strftime指令。

#2


1  

Your date format is wrong. You have days and months reversed. It should be:

您的日期格式错误。你的日子和月份颠倒了。应该是:

 %m%d%Y

#1


2  

You need add parameter errors='coerce' to_datetime, because 13 and 14 months does not exist, so this dates are converted to NaT:

您需要添加参数错误='强制' to_datetime,因为13和14个月不存在,所以这个日期被转换为NaT:

print (pd.to_datetime(df['Date'], format='%d%m%y', errors='coerce'))
0   2016-11-06
1   2016-12-06
2          NaT
3          NaT
Name: Date, dtype: datetime64[ns]

Or maybe you need swap months with days:

或者你需要用几天来交换:

print (pd.to_datetime(df['Date'], format='%m%d%y'))

0   2016-06-11
1   2016-06-12
2   2016-06-13
3   2016-06-14
Name: Date, dtype: datetime64[ns]

EDIT:

编辑:

print (df)
         Date
0  0611160130
1  0612160130
2  0613160130
3  0614160130

print (pd.to_datetime(df['Date'], format='%m%d%y%H%M', errors='coerce'))
0   2016-06-11 01:30:00
1   2016-06-12 01:30:00
2   2016-06-13 01:30:00
3   2016-06-14 01:30:00
Name: Date, dtype: datetime64[ns]

Python's strftime directives.

Python的strftime指令。

#2


1  

Your date format is wrong. You have days and months reversed. It should be:

您的日期格式错误。你的日子和月份颠倒了。应该是:

 %m%d%Y