python两个时间内的工作日_如何在Python中找到两个日期之间的星期一或任何其他工作日的数目?...
這是高效的-即使在開始和結(jié)束之間有一萬天的時(shí)間-而且仍然非常靈活(它在sum函數(shù)內(nèi)最多迭代7次):def intervening_weekdays(start, end, inclusive=True, weekdays=[0, 1, 2, 3, 4]):
if isinstance(start, datetime.datetime):
start = start.date() # make a date from a datetime
if isinstance(end, datetime.datetime):
end = end.date() # make a date from a datetime
if end < start:
# you can opt to return 0 or swap the dates around instead
raise ValueError("start date must be before end date")
if inclusive:
end += datetime.timedelta(days=1) # correct for inclusivity
try:
# collapse duplicate weekdays
weekdays = {weekday % 7 for weekday in weekdays}
except TypeError:
weekdays = [weekdays % 7]
ref = datetime.date.today() # choose a reference date
ref -= datetime.timedelta(days=ref.weekday()) # and normalize its weekday
# sum up all selected weekdays (max 7 iterations)
return sum((ref_plus - start).days // 7 - (ref_plus - end).days // 7
for ref_plus in
(ref + datetime.timedelta(days=weekday) for weekday in weekdays))
這將分別為start和{}獲取{}和{}的{}對(duì)象。在
另外,您可以在閉合(inclusive=True)和半開(inclusive=False)間隔之間進(jìn)行選擇。在
默認(rèn)情況下,它計(jì)算日期之間的工作日數(shù),但也可以選擇任意一組工作日(周末:weekdays=[5, 6])或單個(gè)工作日(星期三:weekdays=2)。在
總結(jié)
以上是生活随笔為你收集整理的python两个时间内的工作日_如何在Python中找到两个日期之间的星期一或任何其他工作日的数目?...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: garch模型python步骤_GARC
- 下一篇: python表情符号编码大全_Emoji