简体   繁体   English

将具有多种日期格式的 dataframe 行转换为日期时间

[英]Converting a dataframe row with multiple date formats into a datetime

I have a dataframe that has two rows that need to be in datetime format so I can use them for calculations.我有一个 dataframe 有两行需要采用日期时间格式,以便我可以将它们用于计算。

They are currently stored as strings in the formats dd/mm/yyyy mm/dd/yyyy mm/dd/yy它们当前以 dd/mm/yyyy mm/dd/yyyy mm/dd/yy 格式存储为字符串

How can I convert them all into a singular format?如何将它们全部转换为单一格式? I have tried using我试过使用

dataframe['ADMISSION_DATE'] =pd.to_datetime(dataframe['ADMISSION_DATE'], format='%m%d%y').dt.strftime('%m/%d/%Y')

Rows that need to be changed需要更改的行

Assuming my assumption in the comment holds true, you can use this:假设我在评论中的假设成立,您可以使用:

pd.to_datetime(df["ADMISSION_DATE"], format="%m/%d/%Y", errors="coerce"). \
    fillna(pd.to_datetime(df["ADMISSION_DATE"], format="%m/%d/%y", errors="coerce"))

You basically try to convert using the first format and whenever this fails, you try the second format.您基本上尝试使用第一种格式进行转换,只要失败,您就尝试第二种格式。

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

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