给定一个datetime.date 对象,您可以使用.isoweekday 方法检查星期几,所有工作日返回值<=5 所以:
def is_business_day(day):
return day.isoweekday() < 5
您可以像这样使用它来查找给定月份中的所有工作日
In [29]: filter(lambda x: x[0] if x[1] else None,
[(d, is_business_day(datetime.date(2017,5,d)))
for d in range(1,31)])
Out[29]:
[(1, True),
(2, True),
(3, True),
(4, True),
(8, True),
(9, True),
(10, True),
(11, True),
(15, True),
(16, True),
(17, True),
(18, True),
(22, True),
(23, True),
(24, True),
(25, True),
(29, True),
(30, True)]
不过,这段代码并不安全。它不检查一个月的边界。
In [34]: filter(lambda x: x[1] if x[1] else None,
[(d, is_business_day(datetime.date(2017,2,d)))
for d in range(1,31)])
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-34-486d782346bd> in <module>()
----> 1 filter(lambda x: x[1] if x[1] else None, [(d, is_business_day(datetime.date(2017,2,d))) for d in range(1,31)])
ValueError: day is out of range for month
因此,您将不得不制定更多逻辑来确定月份的界限。
要弄清楚每个月的界限,请参阅How to find number of days in the current month
你也可以稍微改进一下输出的格式:
In [43]: [d for d in range(1,31) if is_business_day(datetime.date(2017,5,d))]
Out[43]: [1, 2, 3, 4, 8, 9, 10, 11, 15, 16, 17, 18, 22, 23, 24, 25, 29, 30]
更新,现在OP的最后一条评论发布了,获取第X个工作日:
基于最新的列表计算,如果x 是第 9 个工作日:
In [6]: [d for d in range(1,31) if
is_business_day(datetime.date(2017,5,d))][9-1]
Out[6]: 15
In [7]: x=9
In [8]: [d for d in range(1,31) if
is_business_day(datetime.date(2017,5,d))][x-1]
Out[8]: 15