calendar 本月_Python零基础入门学习15:常用标准库之calendar库

:本文所有代码均经过Python 3.7实际运行检验,保证其严谨性。

973816c3ed2adbc3fbabc3c36d4660d8.png

日历

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值