Home > Software engineering >  How do I convert date from alphabetical to numeric format?
How do I convert date from alphabetical to numeric format?

Time:11-30

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')

CodePudding user response:

  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

CodePudding user response:

Try:

pd.to_datetime(df['date'], format='%b %d, %Y').dt.strftime('%Y-%m-%d')

It should work provided all df['date'] entries match the date pattern of 'Sep 17, 2021'.

  • Related