Search code examples
windowspython-3.xdate-formattinglocate

String to Date Format as DD/MM/YYY in Python - Portuguese


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?


Solution

  • 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'