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 do I convert date from alphabetical to numeric format?

I want to convert date from ‘Sep 17, 2021’ format to ‘17.09.2021’. I made a function, but I can’t apply it to the series. What am I doing wrong?

def to_normal_date(bad_date):
    datetime.strptime(bad_date, '%b %d, %Y')
    return s.strftime('%Y-%m-%d')

df['normal_date'] = df['date'].apply(to_normal_date)

I receive a ValueError when I’m trying to apply it to series. But it works fine with this:

to_normal_date('Sep 16, 2021')

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 :

  1. Use pd.to_datetime to convert the "date" column to datetime format. Specifying errors="coerce" will convert dates that are not in the correct format to NaN values instead of raising errors.
  2. Convert to the required format using .strftime with the .dt accessor.
df["normal_date"] = pd.to_datetime(df["date"], format="%b %d, %Y", errors="coerce").dt.strftime("%d.%m.%Y")

>>> df
           date normal_date
0  Sep 17, 2021  17.09.2021
1  Oct 31, 2021  31.10.2021
2  Nov 19, 2021  19.11.2021
3  Dec 25, 2021  25.12.2021
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