6

I would like to convert the string "23/02/2018" to a date format as 23-fev-2018.

Most importanly is that, the month must be in portuguese language, refering to fevereiro.

My issue is that usually the datetime.date prints like (YYYY,MM,DD):

import datetime 
datestr = "23/02/2018" 
dateobj = datetime.datetime.strptime(datestr, "%d/%m/%Y")
print dateobj #year, month, day

How may I print from a string as 23/10/2017 to date format as 23-out-2017, refering to the month "outubro" in portuguese?

1 Answers1

10

Use the locale module.

import locale
import datetime

locale.setlocale(locale.LC_ALL, 'pt_pt.UTF-8')
datetime.datetime.strptime('23/10/2017', '%d/%m/%Y').strftime('%d/%B/%Y')
# '23/Outubro/2017'
datetime.datetime.strptime('23/10/2017', '%d/%m/%Y').strftime('%d/%b/%Y')
# '23/Out/2017'
jackotonye
  • 3,537
  • 23
  • 31
  • What's wrong with mine? > import locale > locale.setlocale(locale.LC_ALL, 'pt_pt.UTF-8') > datestr = "23/10/2017" > date = datetime.datetime.strptime(datestr, '%d/%m/%Y').strftime('%d/%b/%Y') > print (date) – Ricardo Marques Mar 13 '18 at 23:55
  • The bug is called in line 2: > locale.Error: unsupported locale setting Please, may I have to install any module via command line? – Ricardo Marques Mar 14 '18 at 00:02
  • You should check your locales using `[(l, ll) for l, ll in locale.locale_alias.items() if 'pt' in l]` – jackotonye Mar 14 '18 at 09:53
  • Please, I have two comments: [...] 1st) I've seen that the locale.locale_alias does not work in Windows. I still do not know what to do. [...] 2nd) One step back, the strftime prints a string type variable, which is not what I want. I would like to have a date type variable in order to write it on a .xls file. [...] Note: When I write a date type variable on .xls file, It displays as "43182". – Ricardo Marques Mar 14 '18 at 19:45