利用python实现万年历的查询
作者:诗一样的代码 时间:2023-02-24 03:16:01
今天要用python做一个小功能,那就是实现万年历的查询。
首先看一下整体感觉
实现代码:
def is_leap_year(year):
if year/4==0 and year/400 !=0:
return True
elif year/100 == 0 and year/400 ==0 :
return True
else:
return False
首先判断是否是闰年,因为计算2月是否有29天有用。
def getMonthDays(year,month):
days = 31 #31天居多,设置为默认值
if month == 2 : #2月份要判断是否是闰年
if is_leap_year(year):
days=29
else:
days=28;
elif month in [4,6,9,11]: #判断小月,只有30天
days=30
return days
由年和月份获取指定年月的月份有多少天。
def getTotalDays(year,month):
totalDays=0
for i in range(1990,year): #使用range来循环,算出多少年多少天
if is_leap_year(i): #判断是否是闰年
totalDays += 366
else:
totalDays += 365
for i in range(1,month): #使用range循环,算出今年前面几个月过了多少天
totalDays +=getMonthDays(year,i)
return totalDays
获取1990-01-01离现在有多少天,1990-01-01是星期一,以这个为标准来判断。
if __name__ == '__main__':
while True:
print "××××××××××python实现万年历××××××××"
year = raw_input("请输入年份(如:1990):")
month = raw_input("请输入月份:如:1")
try:
year = int(year)
month = int(month)
if month <1 or month >1:
print "年份或者月份输入错误,请重新输入!"
continue
except:
print "年份或者月份输入错误,请重新输入!"
continue
break
print "日\t一\t二\t三\t四\t五\t六"
iCount = 0 #计数器来判断是否换行
for i in range(getTotalDays(year,month)%7):
print '\t', #输出空不换行
iCount+=1
for i in range(1,getMonthDays(year,month)):
print i,
print '\t',
iCount +=1
if iCount%7 == 0 : #计数器取余为0,换行
print ''
最后只需要输入年份和月份,就能把完整的整个月份的日历打出来。无论是查询以前的日历还是查询未来的日历,都是可以计算出来的。
来源:https://juejin.cn/post/7013935530123493406
标签:python,万年历,查询
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python实现用户名密码校验
2022-12-14 07:48:33
![](https://img.aspxhome.com/file/2023/4/70684_0s.jpg)
PHP实现通过二维数组键值获取一维键名操作示例
2023-11-22 12:00:52
Python获取航线信息并且制作成图的讲解
2023-08-28 18:18:56
![](https://img.aspxhome.com/file/2023/6/61986_0s.png)
asp vbcrlf是什么意思
2011-03-30 11:03:00
Python用list或dict字段模式读取文件的方法
2022-07-16 18:29:07
PyQT实现菜单中的复制,全选和清空的功能的方法
2023-08-13 03:09:23
PHP设计模式之观察者模式浅析
2023-05-27 12:20:11
python requests库爬取豆瓣电视剧数据并保存到本地详解
2022-05-29 08:35:05
![](https://img.aspxhome.com/file/2023/0/92190_0s.png)
PHP PDOStatement::bindParam讲解
2023-06-05 05:47:28
如何使用Python破解ZIP或RAR压缩文件密码
2022-03-24 19:28:45
![](https://img.aspxhome.com/file/2023/5/92055_0s.png)
Python实现计算文件MD5和SHA1的方法示例
2023-12-07 06:55:46
PHP如何实现HTTP验证
2023-09-04 05:32:46
Javascript命名禁区[110407.updated]
2011-04-28 09:48:00
Python实现测试磁盘性能的方法
2022-01-31 19:00:46
django settings.py配置文件的详细介绍
2022-09-20 07:40:33
Python之Pygame的Draw绘图
2022-11-29 18:51:18
浅谈python在提示符下使用open打开文件失败的原因及解决方法
2023-12-07 18:31:33
![](https://img.aspxhome.com/file/2023/0/72860_0s.jpg)
Swin Transformer模块集成到YOLOv5目标检测算法中实现
2021-09-10 21:09:49
最全的MYSQL备份方法
2009-12-29 10:19:00
如何在Python中将字符串转换为数组详解
2021-09-10 06:36:09
![](https://img.aspxhome.com/file/2023/6/83866_0s.png)