本章介绍python的农历库——calendar。该库用得不多,但某些场合下,却很需要它。
1. calendar.calendar(theyear, w=2, l=1, c=6, m=3)
输出指定年的每个月的农历信息。返回固定格式的字符串。
theyear:年份
w:每列的宽度
l: 每行之间的高度
c:两个月份块之间的宽度
m:每行显示多少个月份
import calendar
print(calendar.calendar(2018,w=3,l=1,c=8,m=4))

2. calendar.prcal(theyear, w=0, l=0, c=6, m=3)
与 1 一样,只是不用写print也能输出。返回固定格式的字符串。
calendar.prcal(2018,w=3,l=1,c=8,m=4)

3. calendar.month(theyear, themonth, w=0, l=0)
输出指定年月的农历信息。返回固定格式的字符串。
theyear:年份
themonth:月份
w:每列的宽度
l: 每行之间的高度
print(calendar.month(theyear=2019,themonth=2,w=3,l=1))

4. calendar.prmonth(theyear, w=0, l=0, c=6, m=3)
与 3 一样,只是不用写print也能输出。返回固定格式的字符串。
calendar.prmonth(theyear=2019,themonth=2,w=3,l=1)

5. calendar.monthcalendar(year, month)
返回指定年月的农历信息。返回列表。
year:指定年
month:指定月
print(calendar.monthcalendar(2019,2))

6. calendar.isleap(year)
是否为闰年。
year:指定年
print(calendar.isleap(1900))

7. calendar.leapdays(y1, y2)
返回一个时间段里的闰年数。区间为左闭右开[y1,y2),且y1<y2。
print(calendar.leapdays(1949,2022))

8. calendar.monthrange(year, month)
返回一个元组,元组第一个为模糊星期几(0为星期一,1为星期而二,以此类推),第二个为该月的天数
print(calendar.monthrange(2019,2))

9. calendar.weekday(year, month, day)
输出某一天为模糊星期几。输出1即为星期二。
print(calendar.weekday(2019,2,5))

10. calendar.Calendar.itermonthdates(self, year, month)
连续输出某月的所有天数,返回字符串。(会填补空缺)
self:类的返回参数,无需理会
year:指定年
month:指定月
mon = calendar.Calendar().itermonthdates(2019,2)
for day in mon:
print(day)

有的小伙伴会疑惑,为什么2019年2月的输出结果包含了1月尾和3月初呢?答案在于图4,回去看就明白啦!格子里空余的那几天它用了上个月和下个月的去填补。
11. calendar.Calendar.itermonthdays3(self, year, month)
连续输出某月的所有天数,返回元组。
ld = calendar.Calendar().itermonthdays3(2019,2)
for i in ld:
print(i)

可以看到该函数返回的是一个元组,对于第10的问题,如果我们只想输出2月份,那么可以用一个if判断语句即可。如下:
ld = calendar.Calendar().itermonthdays3(2019,2)
for j in ld:
if j[1] == 2:
l = [str(k) for k in j]
print('-'.join(l))
python各库之间具有很强的交互性,calendar输出的格式也可以运用在time和datetime等日期时间库中,即使不行,也可以通过strptime和strftime相互转换。