天天看點

python 月曆_Python月曆:指定的日/月名稱

這是來自calendar子產品的源代碼: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)

可以從calendar子產品導入TimeEncoding和month_name。這提供了以下方法: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")

對我來說,不需要解碼步驟,隻要在TimeEncoding上下文中列印month_name[3]就可以列印“mars”,這是挪威語的“march”。

對于工作日,也有類似的方法使用day_name和day_abbr指令: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