[英]How to convert two different date formats from a pandas dataframe column into same format?
I have two different date formats in a pandas column such as - DD-MM-YYYY
and MM/DD/YYYY
and I want to convert them into the same format.我在 pandas 列中有两种不同的日期格式,例如 - DD-MM-YYYY
和MM/DD/YYYY
,我想将它们转换为相同的格式。
I tried using the code -我尝试使用代码 -
data['SALE DATE'] = pd.to_datetime(data['SALE DATE']).dt.strftime('%m/%d/%Y')
but this converts the dates into DD/MM/YYYY
and MM/DD/YYYY
into the output - data['SALE DATE']但这会将日期转换为DD/MM/YYYY
和MM/DD/YYYY
转换为 output - data['SALE DATE']
I want a python solution to overcome this problem.我想要一个 python 解决方案来克服这个问题。 Any leads will be very helpful.任何线索都会非常有帮助。
The most intuitive solution is to write a custom conversion function, someting like:最直观的解决方案是编写自定义转换 function,类似于:
def myDateConv(tt):
sep = tt[2]
if sep == '-':
return pd.to_datetime(tt, format='%d-%m-%Y')
elif sep == '/':
return pd.to_datetime(tt, format='%m/%d/%Y')
else:
return tt
and then pass it as a converter for the column in question:然后将其作为相关列的转换器传递:
df = pd.read_csv('Input.csv', converters={'Date': myDateConv})
I prepared a CSV file, which read with read_csv without any custom converter gave the original content and both columns of object type:我准备了一个 CSV 文件,它使用read_csv读取,没有任何自定义转换器,给出了原始内容和object类型的两列:
Date Input format
0 03-05-2020 DD-MM-YYYY
1 05/07/2020 MM/DD/YYYY
But reading the same file with the above converter gave:但是用上面的转换器读取相同的文件给出了:
Date Input format
0 2020-05-03 DD-MM-YYYY
1 2020-05-07 MM/DD/YYYY
with Date column of datetime64[ns] type and both dates from May, just as intended.使用datetime64[ns]类型的Date列和从 5 月开始的两个日期,正如预期的那样。
Or if you have this DataFrame from other source and you want to convert this column, run:或者,如果您有来自其他来源的 DataFrame 并且想要转换此列,请运行:
df.Date = df.Date.apply(myDateConv)
If you are using pandas version 1.xx you can use the following solution:如果您使用的是 pandas 版本 1.xx,您可以使用以下解决方案:
pd.to_datetime(["11-08-2018", "05-03-2016", "08/30/2017", "09/21/2018"], infer_datetime_format=True, dayfirst=True).strftime("%m/%d/%Y")
This gives the following result:这给出了以下结果:
Index(['08/11/2018', '03/05/2016', '08/30/2017', '09/21/2018'], dtype='object')
... the important argument here is dayfirst=True . ...这里的重要论点是dayfirst=True 。
See pd.to_datetime
docs for more.有关更多信息,请参阅pd.to_datetime
文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.