Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Localized month name in Python

I'd like to have localized months name automatically given by Python.

I use this piece of code : datetime.datetime.strptime(j, "%m").strftime("%B") where j is the month number.

My problem is that it keeps giving me "January" while I'm expecting "Janvier" (french locale).

I tried to play a little with locale and the only way I found to make it work is to call locale.set_locale(locale.LC_ALL, "") at the begining of the script.

Is it the good way to go ? Or is there any problem and nicer solutions ?

Thanks

like image 748
Phyks Avatar asked Jul 27 '13 21:07

Phyks


People also ask

How to get month names in Python?

We can use two ways to get the month name from a number in Python. The first is the calendar module, and the second is the strftime() method of a datetime module. The below steps show how to get the month name from a number in Python using the calendar module. Calendar is a built-in module available in Python.

How do I convert a number to a month in Python?

datetime. strptime() is called. It takes month number and month format "%m" as arguments. Passing "%b" to strftime returns abbreviated month name while using "%B" returns full month name.


2 Answers

If you have your locale set at the OS level,

locale.set_locale(locale.LC_ALL, '')
print locale.nl_langinfo(locale.LC_MON1)

"janvier"

Or you can set it at python level:

 locale.set_locale(locale.LC_ALL, 'fr_FR')
 print locale.nl_langinfo(locale.LC_MON1)

 "janvier"
like image 138
swstephe Avatar answered Oct 23 '22 16:10

swstephe


If you only wan't it to affect the datetime function try this:

def getLocalizedMonth(j):
  locale.setlocale(locale.LC_ALL, "")
  datetime.datetime.strptime(j, "%m").strftime("%B")
  locale.setlocale(locale.getdefaultlocale())

And yes I think using the locale.setlocale is the best solution!

like image 26
Jenrik Avatar answered Oct 23 '22 17:10

Jenrik