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
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.
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.
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"
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With