未来一段时间,每个月有几个礼拜几?

题目

未来一段时间内(一年或者几年或者几个月,按月为最小单位),其中的每个月里,会出现几个星期几(一二三四五六七)?

场景

设置定时任务,周期为每个月4次,并且是每个月的固定前4个星期几去执行。

说明:每个月会有不固定个数的星期几是会出现五次的(1个或最多3个吧),所以需要提前一段时间预判一下未来的情况,也许有其他的场景也是类似。
也想过每7天执行一次,最多4次的方法,不过还是感觉有点不同的。
总之还是需要先整出来看看。

哪位大神无聊了写个方法出来吧,语言也不限制啊,别用太低级的语言就行了,有注释的话更好哈。


回答:

用的Python :

from datetime import datetime, timedelta

def count_weekdays(start_date, end_date, weekday):

start_date = datetime.strptime(start_date, '%Y-%m-%d')

end_date = datetime.strptime(end_date, '%Y-%m-%d')

current_date = start_date

month_count = {}

while current_date <= end_date:

current_month = current_date.strftime('%Y-%m')

if current_date.weekday() == weekday:

if current_month not in month_count:

month_count[current_month] = 0

month_count[current_month] += 1

current_date += timedelta(days=1)

return month_count

# 用法:

start_date = '2023-05-01'

end_date = '2024-04-30'

weekday_to_count = 2 # 0 for Monday, 1 for Tuesday, etc.

print(count_weekdays(start_date, end_date, weekday_to_count))

以上是 未来一段时间,每个月有几个礼拜几? 的全部内容, 来源链接: utcz.com/p/945154.html

回到顶部