Calendar: day/month names in specific locale Calendar: day/month names in specific locale python python

Calendar: day/month names in specific locale


Ha! Found an easy way to get localized day/month names:

>>> import locale>>> locale.setlocale(locale.LC_ALL, 'de_DE')'de_DE'>>> import calendar>>> calendar.month_name[10]'Oktober'>>> calendar.day_name[1]'Dienstag'


This is from the source code of the calendar module:

def formatmonthname(self, theyear, themonth, width, withyear=True):    with TimeEncoding(self.locale) as encoding:        s = month_name[themonth]        if encoding is not None:            s = s.decode(encoding)        if withyear:            s = "%s %r" % (s, theyear)        return s.center(width)

TimeEncoding and month_name can be imported from the calendar module. This gives the following method:

from calendar import TimeEncoding, month_namedef get_month_name(month_no, locale):    with TimeEncoding(locale) as encoding:        s = month_name[month_no]        if encoding is not None:            s = s.decode(encoding)        return sprint get_month_name(3, "nb_NO.UTF-8")

For me the decode step is not needed, simply printing month_name[3] in the TimeEncoding context prints "mars", which is norwegian for "march".

For weekdays there's a similar method using the day_name and day_abbr dicts:

from calendar import TimeEncoding, day_name, day_abbrdef get_day_name(day_no, locale, short=False):    with TimeEncoding(locale) as encoding:        if short:            s = day_abbr[day_no]        else:            s = day_name[day_no]        if encoding is not None:            s = s.decode(encoding)        return s


Here's the month part of Lauritz's answer updated for Python 3:

from calendar import month_name, different_localedef get_month_name(month_no, locale):    with different_locale(locale):        return month_name[month_no])