Python specifies the number of days in the month, the specified date is the day of the week, the specified month has several Sundays, and the leap year calendar

Python specifies the number of days in the month, the specified date is the day of the week, the specified month has several Sundays, and the leap year calendar

1. Specify the number of days in the month

import calendar
import datetime as dt
date1 = dt.date(2020, 9, 1)
n_days = calendar.monthrange(2020, 9)   # 返回结果:(1, 30)
# calendar.monthrange(year,month):第一个参数:指定月份第一天为周几(0-6 对应 周一 -周日);第二个参数:指定月份的天数

2. Specify the day of the week

week = calendar.weekday(2020,9,23)   # 返回结果:2
# calendar.weekday(year,month,day):(0-6 对应 周一 -周日)

3. Output the specified month

calendar.month(2020, 9)   # 返回结果:'   September 2020\nMo Tu We Th Fr Sa Su\n    1  2  3  4  5  6\n 7  8  9 10 11 12 13\n14 15 16 17 18 19 20\n21 22 23 24 25 26 27\n28 29 30\n'
# calendar.month(year, month):指定月份的多行文本字符串

4. Get all the dates in the specified month

date1 = dt.date(2020,9,1)
dates = [(date1 + dt.timedelta(i)) for i in range(n_days[1])]

5. Calculate the number of Sundays in the specified month

n_sundays = 0
for d in dates:
	n_sundays += int(d.isoweekday() == 6)

6. Leap year
(1) Determine whether the specified month is a leap year

calendar.isleap(2020)   # 返回结果:True
# calendar.isleap(year):闰年为True,平年为False

(2) The number of leap years between two years

calendar.leapdays(2008, 2020)  # 返回结果:3
# calendar.leapdays(year1, year2):year1与year2年份之间的闰年数量(包括起始年,不包括结束年)

Guess you like

Origin blog.csdn.net/weixin_40012554/article/details/108763013