我有两个日期作为datetime.date
对象,在这两个日期(包括开始日期和结束日期除外)之间查找多个工作日的最Python化方法是什么?例如:
from datetime import date, timedelta
d1 = date(2019, 3, 1)
d2 = date(2019, 5, 6)
# The difference between d2 and d1 is 46 workdays
我想写一个循环:
workdays = 0
for i in range((d2 - d1).days):
if (d1 + timedelta(days=i)).isoweekday() <= 5:
workdays += 1
但是,我认为有一种更简单的方法可以解决此问题。
答案 0 :(得分:2)
您可以尝试以下方法:
它不考虑假期,..:
import numpy as np
np.busday_count(d1.strftime("%Y-%m-%d"), d2.strftime("%Y-%m-%d"))
答案 1 :(得分:2)
使用numpy函数busday_count:
from datetime import date
import numpy as np
d1 = date(2019, 3, 1)
d2 = date(2019, 5, 6)
days = np.busday_count( d1, d2 )
print (days)
或
from datetime import date,timedelta
d1 = date(2019, 3, 1)
d2 = date(2019, 5, 6)
daygenerator = (d1 + timedelta(x + 1) for x in range((d2 - d1).days)) # generate all days from d1 to d2
print (sum(1 for day in daygenerator if day.weekday() < 5))