import datetime
def is_leap_year(year):
"""判断给定的年份是否为闰年"""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def days_in_month(year, month):
"""返回给定年月的天数"""
if month in [1, 3, 5, 7, 8, 10, 12]:
return 31
elif month in [4, 6, 9, 11]:
return 30
elif month == 2:
return 29 if is_leap_year(year) else 28
else:
raise ValueError("Invalid month")
def print_month_header(year, month):
"""打印月份头部信息"""
weekdays = ["一", "二", "三", "四", "五", "六", "日"]
print(f"{year}年{month}月")
print(" ".join(weekdays))
def print_month_days(year, month):
"""打印月份的具体日期"""
first_day_of_month = datetime.date(year, month, 1)
offset = first_day_of_month.weekday()
days = days_in_month(year, month)
print(" " * (offset * 3), end="")
for day in range(1, days + 1):
print(f"{day:2d}", end=" ")
if (day + offset) % 7 == 0:
print()
print()
def generate_year_calendar(year):
"""生成指定年份的万年历"""
print(f"以下是{year}年的日历:")
for month in range(1, 13):
print_month_header(year, month)
print_month_days(year, month)
generate_year_calendar(2024)