Calendar: day/month names in specific locale

后端 未结 3 1949
甜味超标
甜味超标 2020-12-17 10:03

I am playing with Python\'s calendar module that\'s in the standard library. Basically I need a list of all days of a month, like so:

>>> import cal         


        
相关标签:
3条回答
  • 2020-12-17 10:21

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

    from calendar import month_name, different_locale
    def get_month_name(month_no, locale):
        with different_locale(locale):
            return month_name[month_no])
    
    0 讨论(0)
  • 2020-12-17 10:33

    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'
    
    0 讨论(0)
  • 2020-12-17 10:39

    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_name
    
    def 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 s
    
    print 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_abbr
    
    def 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
    
    0 讨论(0)
提交回复
热议问题