注:本文所有代码均经过Python 3.7实际运行检验,保证其严谨性。
![973816c3ed2adbc3fbabc3c36d4660d8.png](https://i-blog.csdnimg.cn/blog_migrate/f282a1fdaf6b2e1d1a66e8ef9021187a.jpeg)
日历
calendar模块包含了跟日历相关的若干函数和类,可以生成文本形式的日历。
制作电子日历:一个月 calendar.month(, )——返回某年某月的多行字符串。 calendar.prmonth(, )——相当于print(calendar.month(, ))。
import calendarcalendar.month(2017, 3)Out[2]: ' March 2017Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 1213 14 15 16 17 18 1920 21 22 23 24 25 2627 28 29 30 31'print(calendar.month(2017, 3)) March 2017Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 1213 14 15 16 17 18 1920 21 22 23 24 25 2627 28 29 30 31
制作电子日历:一整年
calendar.calendar()——以多行字符串的形式返回一年的日历的数据。
calendar.prcal()——相当于print(calendar.calendar())。
calendar.calendar(2019) # 输出数据太多,输出从略。calendar.prcal(2019) # 输出数据太多,输出从略。
将日历列表化
calendar.monthcalendar()——返回某一年的某一个月份日历,是一个嵌套列表。最里层的列表包含有7个元素,分别代表周一到周日。如果对应的位置没有本月的日期,则该位置以0代替。
calendar.monthcalendar(2019, 11)Out[6]: [[0, 0, 0, 0, 1, 2, 3], #2019年11月从周五开始,即11月1日是周五。 [4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23, 24], [25, 26, 27, 28, 29, 30, 0]] #2019年11月以周六结束,即11月30日是周六。
判断闰年
闰年分为普通闰年和世纪闰年。
普通闰年——能被4整除,但不能被100整除的年份。比如2016年。
世纪闰年——能被400整除的年份。比如2000年。
calendar.isleap()——判断是否闰年,是则返回True,否则返回False。
calendar.isleap(2018)Out[7]: Falsecalendar.isleap(2020)Out[8]: True
calendar.monthrange(, )——计算某月从周几开始,共有多少天。
calendar.weekday(, , )——计算某个具体日期,如2019年11月21日是星期几。 要注意的是,Python的calendar中,从0到6依次表示周一到周日。
calendar.monthrange(2019, 11)Out[9]: (4, 30) #表示2019年11月从周五开始,一共有4周,calendar.weekday(2019, 11, 21)Out[10]: 3 #表示2019年11月21日是周四(3代表周四)。
To be continued.