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

How can I convert these dates to the correct format in a Pandas Dataframe?

I have a dataframe with some dates and I want to convert them to datetime format. So I used the pd.to_datetime function to do so. However, it only works for some of the dates as the others are not written in the correct order. Example:

df = pd.DataFrame({'dates' : ['December 2021 17', '2005 July 01', 'December 2000 01', '2008 May 11', 
                              'October 2000 04', 'September 2016 04', 'May 1998 09']})

Using pd.to_datetime will only return values for the yy-mm-dd order. I tried splitting these into list and trying to reorder them, but that didn’t seem to work for me.

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

>Solution :

You can use apply and give it to_datetime:

df.dates = df.dates.apply(pd.to_datetime)

This is the output of df now:

       dates
0 2021-12-17
1 2005-07-01
2 2000-12-01
3 2008-05-11
4 2000-10-04
5 2016-09-04
6 1998-05-09
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