当前位置: 首页> 房产> 政策 > 用python纯手写一个日历

用python纯手写一个日历

时间:2025/7/9 7:16:24来源:https://blog.csdn.net/weixin_58573288/article/details/139694061 浏览次数:0次

一、代码

# 月份名称数组
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 += dreturn all_days# 得到某年某月某日是星期几
def week(y, m, d):all_days = 0if y == 1940:all_days = year_days(y, m, d) - 1else:# 计算总天数,包括闰年的额外一天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) - 1get = (all_days + 1) % 7return 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] = -1else:flag[a] = date - week1else:flag[a] = -1date += 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()

二、运行结果

关键字:用python纯手写一个日历

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: