Skip to main content
 首页 » 编程设计

python之pd.to_datetime 是我一半的日期与翻转的日期/月份

2024年09月07日9mfrbuaa

我的数据集有欧洲格式的日期,在我通过 pd.to_datetime 传递它之前,我正在努力将它转换成正确的格式,所以对于 < 12 日的一整天,我的月份和日期切换。 对此有简单的解决方案吗?

import pandas as pd 
import datetime as dt 
df = pd.read_csv(loc,dayfirst=True) 
df['Date']=pd.to_datetime(df['Date']) 

有没有办法强制 datetime 确认输入的格式为 dd/mm/yy?

感谢您的帮助!

编辑,我约会的样本:

renewal["Date"].head() 
Out[235]:  
0    31/03/2018 
2    30/04/2018 
3    28/02/2018 
4    30/04/2018 
5    31/03/2018 
Name: Earliest renewal date, dtype: object 

运行以下命令后:

renewal['Date']=pd.to_datetime(renewal['Date'],dayfirst=True) 

我得到:

Out[241]:  
0    2018-03-31  #Correct 
2    2018-04-01   #<-- this number is wrong and should be 01-04 instad 
3    2018-02-28   #Correct 

请您参考如下方法:

添加format .

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