0

I would like to convert dates (Before) within a column (After) in 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 as 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 me how to do it?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • 1
    `"%y-%m-%d"` is certainly not `dd mm yyyy` as the title asks. Also `"%d %m, %y"` is not the format that `Before` comes in, which is `'%d %B %Y'`. That said, did you try `pd.to_datetime(df['Before']).dt.strftime('%d-%m-%Y')`? – Quang Hoang Oct 30 '20 at 20:55
  • check out https://strftime.org/ for the correct format codes - anyway, I think the important point here is to set the locale so that the non-English month names are parsed correctly. – FObersteiner Oct 30 '20 at 21:08
  • Thank you so much! will edit it right now –  Oct 30 '20 at 22:04

1 Answers1

0

Similar to this question, you can set the locale to 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 the "After" column as dtype string, use df['After'].dt.strftime('%Y-%m-%d').

FObersteiner
  • 22,500
  • 8
  • 42
  • 72