-1

I have a date column with the format 19 dic 2020 23:59 (spanish date) and I want to convert it into a datetime type.

df["Time"] = pd.to_datetime(df.Time, format='%d %b %Y %H:%M', errors = "coerce")

After running the code column is the right type datetime but it only contains NaT values.

what am I doing wrong?

enter image description here

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • what is 'dic' should that be 'dec'? – adir abargil Dec 22 '20 at 13:49
  • 1
    @adirabargil Rather country-specific datetime format. This should be specified in the question. Ignacio: Please do not post images of code/data/error messages. Post the text directly here on SO. – Mr. T Dec 22 '20 at 13:51

2 Answers2

3

I believe this is an error that is associated with pandas' function not supporting other locales such as es_ES as in your case. I would recommend changing the locale or iterating as is described in these two answers. The first uses a locale change via datetime and the second recommends using substitution.

  1. Converting spanish date into python pandas datetime object with locale setting
  2. Pandas to datetime with German date format?
Aasim Sani
  • 339
  • 2
  • 6
  • SO has the duplicate flag for a reason – Mr. T Dec 22 '20 at 13:55
  • for `%b`, the spanish month name abbreviation input must be e.g. `dic.`; notice the dot. this is neither a pandas nor a locale problem - even if you set the locale correctly, you still need to supply the correct input to strptime. – FObersteiner Dec 22 '20 at 15:02
1

This is neither a pandas nor a locale problem. For one, your strptime directive is slightly wrong, and second, your input just doesn't match %b. pd.to_datetime works fine if you set the correct locale, supply the correct input and set the correct format directive:

import locale
locale.setlocale(locale.LC_ALL, 'es_ES')

import pandas as pd

s = '19 dic 2020 23:59'
print(pd.to_datetime(s.replace('dic', 'dic.'), format='%d %b %Y %H:%M'))
# 2020-12-19 23:59:00
FObersteiner
  • 22,500
  • 8
  • 42
  • 72