Datetime Does Not Recognize Abbreviated Months When Parsing Dates in Spanish

106 Views Asked by At

I'm trying to parse dates of the form "Ago de 2022" in Spanish in Python. For some reason, the dateparser module is not working on my machine, so I'm doing this manually with the datetime package. When using a Spanish locale, the strptime method seems unable to recognize dates with abbreviated months.

Here is some sample code that demonstrates the problem

import locale
from datetime import datetime as dt

locale.setlocale(locale.LC_ALL, 'esp_esp.utf-8')


format=r"%b-%Y"
dt.strptime("Sep-2022", format)

Returns an error: time data 'Sep-2022' does not match format '%b-%Y'.

Now for some other cases to provide insight. The following code runs just fine:

import locale
from datetime import datetime as dt

locale.setlocale(locale.LC_ALL, 'esp_esp.utf-8')


format=r"%B-%Y"
dt.strptime("Septiembre-2022", format)

So the issue is only for abbreviated months it seems. Further, the English seems to work just fine! The following code runs fine:

import locale
from datetime import datetime as dt

locale.setlocale(locale.LC_ALL, 'en_US.utf-8')


format=r"%b-%Y"
dt.strptime("Sep-2022", format)

I'm working in a Jupyter Notebook running Python 3.9.13.

0

There are 0 best solutions below