How to convert a string to Date with the month name in English

Asked

Viewed 1,062 times

1

I have a df in which the first column dates (13-mai-2019) is as string and I want to convert her to 13-Maio-2019 or 13-5-2019.

I used the following code:

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

But I get the following mistake:

Valueerror: time data '13-may-2019' does not match format '%d-%B-%Y'

  • '13-mai-2019' is not within the expected format, but '13-May-2019' is. Your application is properly configured with the correct location?

  • I am taking information from an excel file, in which I recorded as csv.

  • But that doesn’t answer the location setting. If you have a date in English, you have configured Python to work with that location?

  • I’m sorry, I’m starting on pandas, I have some difficulty, the locale seems to be in Portuguese, I can see how?

1 answer

4

There is an error and a potential problem in its application.

The error is that the formatting set by %B awaits the full name of the month, while in the value to be treated you have only the reduced name. That is, the %B you would use only if you possessed the date as '13-maio-2019'. As it has the name reduced, need to use %b, in lowercase.

The potential problem is that you have the date in Portuguese and by default Python is located to work with the values in English. To correct the location you need to use the module locale:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'pt_BR.utf8')

And from that date, your date will be treated correctly:

>>> from datetime import datetime
>>> datetime.strptime('13-Mai-2019', '%d-%b-%Y')
datetime.datetime(2019, 5, 13, 0, 0)

To check the current location, just check the value returned by locale.getlocale(). It is worth remembering that the module locale will use C libraries to do this management, which depend directly on your operating system settings. To check what are the possible values for your OS currently just run the command locale -a in the terminal.

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.