参数var_year = 2022 是年份 参数var_weeks = 4 是选第N(个)周 参数var_weekday = 5 星期 最后输出每个月对应的日期。
'''
一年中每个月第四个周五。
'''
from datetime import datetime, timedelta
var_year = 2022 ##年份
var_weeks = 4 ##第几周
var_weekday = 5 ##周几
assert 0 < var_weekday < 8 and isinstance(
var_weekday,
int), f'weekday is {var_weekday} it must be int and number(1-7)'
assert 0 < var_weeks < 5 and isinstance(
var_weeks, int), f'weeks is {var_weeks} , it must be int and number(1-4)'
for i in range(1, 13):
var_month = i
var_day = 1
tmp_date = datetime(var_year, var_month, var_day)
for j in range(var_weeks):
while tmp_date.isoweekday() != var_weekday:
tmp_date = tmp_date + timedelta(days=1)
if j == var_weeks - 1:
continue
tmp_date = tmp_date + timedelta(days=1)
print(tmp_date)
运行结果:
2022-01-28 00:00:00
2022-02-25 00:00:00
2022-03-25 00:00:00
2022-04-22 00:00:00
2022-05-27 00:00:00
2022-06-24 00:00:00
2022-07-22 00:00:00
2022-08-26 00:00:00
2022-09-23 00:00:00
2022-10-28 00:00:00
2022-11-25 00:00:00
2022-12-23 00:00:00