Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)
edited by

I would like to convert the dates (Before) within the column (After) in the date format:

Before                      After

23 Ottobre 2020          2020-10-23

24 Ottobre 2020          2020-10-24

27 Ottobre 2020          2020-10-27

30 Ottobre 2020          2020-10-30

22 Luglio 2020           2020-07-22

I tried the follows:

from datetime import datetime

date = df.Before.tolist()

dtObject = datetime.strptime(date,"%d %m, %y")

dtConverted = dtObject.strftime("%y-%m-%d")

But it does not work. Can you explain to me how to do it?

1 Answer

0 votes
by (36.8k points)

You need to set the locale to the italian before parsing:

import pandas as pd

import locale

locale.setlocale(locale.LC_ALL, 'it_IT')

df = pd.DataFrame({'Before': ['30 Ottobre 2020', '22 Luglio 2020']})

df['After'] = pd.to_datetime(df['Before'], format='%d %B %Y')

# df

#             Before      After

# 0  30 Ottobre 2020 2020-10-30

# 1   22 Luglio 2020 2020-07-22

If you want "After" column as the dtype string, use df['After'].dt.strftime('%Y-%m-%d').

Want to be a master in Data Science? Enroll in this Data Science Courses

Browse Categories

...