Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert string to date with multiple formats

I have dates in the following format in the same file:

"%m/%d/%Y" --> YEAR with 4 digits
"%m/%d/%y" --> YEAR with 2 digits

I want to be able to parse both formats. Here’s my attempt:

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

But that is not working:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ValueError: to assemble mappings requires at least that [year, month, day] be specified: [day,month,year] is missing

If I try with only one serie:

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

I get ValueError and doesn’t seem like both formats are being tested.

ValueError: unconverted data remains: 21

What is the most efficient way to use different date formats?

>Solution :

IIUC, Just remove the format parameter from pd.to_datetime and let the inherit formatting handle the change from two digit years to four digit years.

pd.to_datetime(pd.Series(['01/01/2023', '01/02/23', '12/24/2021', '11/23/21']))

Output:

0   2023-01-01
1   2023-01-02
2   2021-12-24
3   2021-11-23
dtype: datetime64[ns]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading