to_datetime无法识别大熊猫日期为'20 Oct 2015'

问题描述 投票:0回答:1

我有一个提取多种格式日期的代码。然后,我使用pd.to_datetime转换字符串以进行排序。但是,它不会更改日期的中间列。

x = dates[0].str.extract(r'(\d{1,2}?[/-]\d{1,2}[/-]\d{2,4})|((?:\d{1,2} )?(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*[-., ]*(?:\d{1,2})?[rd|st|th|nd]?[,]?[- ]\d{4})|(\d{4})') 

#reformat dates 
x[0] = pd.to_datetime(x[0],infer_datetime_format=True)
x[1] = pd.to_datetime(x[1],exact=False,errors = 'ignore')
x[2] = pd.to_datetime(x[2],infer_datetime_format=True,errors = 'coerce' )
#sort
#return the index column 
y = pd.Series(x.sort_values(by=[0, 1,2]).index)

这将按原样返回中间列,而不会更改日期。

Here is a screen shot of the output

我检查了数据并尝试了各种格式的多个日期,它们都可以单独工作。是否存在该列中的日期具有不同格式的问题-有些日期在第一天,有些日期在第二天等等?

Here is a screen shot of the data in the column

python pandas datetime
1个回答
1
投票

您必须正确指定str-to-date格式。要转换“ 2015年10月20日”,请使用以下代码:

pd.to_datetime("20 Oct 2015", format='%d %b %Y')

它将返回:

Timestamp('2015-10-20 00:00:00')

时间格式指令列表在这里:http://strftime.org/

© www.soinside.com 2019 - 2024. All rights reserved.