A. Esquivias
A. Esquivias

Reputation: 260

Change date format with pandas

I have a data frame with a column 'object type' called 'Fecha' and I would like to cast it as DateTime type. However, pandas cannot recognize the format as it is some kind of Spanish format (i.e: '1 abr, 2019'). What should I do to change to a standard format like dd/mm/yyyy?

Abr corresponds to Abril which is April in English.

Fecha column

I have tried with pd.to_datetime() and strftime method but pandas cannot recognize the format.

ValueError: ('Unknown string format:', '1 abr. 2019')

Greetings and thanks in advance

Upvotes: 0

Views: 697

Answers (1)

Juan Estevez
Juan Estevez

Reputation: 866

If you set the locale to es_ES you can convert the string series to datetime using pd.to_datetime and the appropriate format codes from here.

In this case the format code is %d %b %Y (well, not exactly since the days are not zero padded, but pd.to_datetime doesn't seem to care).

import locale
locale.setlocale(locale.LC_TIME, locale='es_ES')

df['Fecha'] = pd.to_datetime(df['Fecha'], format='%d %b %Y')

Upvotes: 2

Related Questions