- # 月份名称数组
- months = [
- "January", "February", "March", "April", "May", "June",
- "July", "August", "September", "October", "November", "December"
- ]
- # 每月天数数组
- month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
-
-
- # 判断是否是闰年
- def leap_year(y):
- if (y % 100 != 0 and y % 4 == 0) or (y % 400 == 0):
- month_days[1] += 1
-
-
- # 计算某年某月某日到该年第一月第一日的日数
- def year_days(y, m, d):
- all_days = 0
- # 判断是否是闰年,闰年二月有29天
- leap_year(y)
- # 计算总日数
- for i in range(m - 1):
- all_days += month_days[i]
- all_days += d
- return all_days
-
-
- # 得到某年某月某日是星期几
- def week(y, m, d):
- all_days = 0
- if y == 1940:
- all_days = year_days(y, m, d) - 1
- else:
- # 计算总天数,包括闰年的额外一天
- for i in range(1940, y):
- all_days += 365 + ((y % 100 != 0 and y % 4 == 0) or (y % 400 == 0))
- all_days += year_days(y, m, d) - 1
- get = (all_days + 1) % 7
- return get
-
-
- # 打印某月的日历
- def show_month(y, m):
- # 判断是否是闰年,闰年二月有29天
- leap_year(y)
- week1 = week(y, m, 1)
- print('{}\n---------------------------'.format(month_days[m - 1]))
- print("Sun Mon Tue Wed Thu Fri Sat")
- date = 1
- # 遍历星期和日期
- while date <= week1 + month_days[m - 1]:
- flag = [0] * 7
- # 遍历一周的每一天
- for a in range(7):
- if date <= (week1 + month_days[m - 1]):
- if date < week1:
- flag[a] = -1
- else:
- flag[a] = date - week1
- else:
- flag[a] = -1
-
- date += 1
-
- # 打印一周的日期
- print(" ".join(f"{-1 if x == 0 else x:<4}" for x in flag))
- print()
-
-
- # 主函数
- def main():
- print("输入要查找的年月份")
- year = input("年:")
- month = input("月:")
- if not (year.isdigit() and month.isdigit()):
- print('请输入一个合法的日期!!!')
- else:
- show_month(int(year), int(month))
-
-
- if __name__ == "__main__":
- main()