首页 > 解决方案 > 使用 Python 中的日历模块确定有 5 个或更多星期日的月份?

问题描述

例如,我需要编写一个代码来查找 2018 年的哪个月有 5 个或更多星期日?我想在 Python 中使用日历模块并以缩写形式保存生成的月份。我看到了日历模块的文档,但无法弄清楚代码。

标签: pythonpython-3.xcalendar

解决方案


这是一种方法。此外,返回https://docs.python.org/3/library/calendar.html并尝试使用其中描述的一些内容。

import calendar

def find_five_sunday_months(year):
    calendar.setfirstweekday(calendar.SUNDAY)
    five_sunday_months = []
    for month in range(1, 13):
        calendar_month = calendar.monthcalendar(year, month)
        # If you're counting Sunday as the first day of the week, then any month that extends into
        # six weeks, or starts on a Sunday and extends into five weeks, will contain five Sundays.
        if len(calendar_month) == 6 or (len(calendar_month) == 5 and calendar_month[0][0] == 1):
            five_sunday_months.append(calendar.month_abbr[month])

    return five_sunday_months

print (find_five_sunday_months(2018))

推荐阅读