你如何在python中获得给定月份的第x个工作日?

时间:2016-05-19 09:04:00

标签: python datetime

如果我有一个月(2017,5),并且我想获得该月的第10个工作日 - 是否有快速的方法可以做到这一点?蛮力,我知道我可以遍历每个日历日,并创建一个大规模的映射。但想知道是否有更简单的方法。

很抱歉,如果之前有人问过这个问题!似乎无法在python中找到解决方案。

2 个答案:

答案 0 :(得分:2)

如果有/** * Reads a code of length 8 in an array of bits, padding with zeros */ private static byte readByte(boolean[] rawbits, int startIndex) { int n = rawbits.length - startIndex; if (n >= 8) { return (byte) readCode(rawbits, startIndex, 8); } return (byte) (readCode(rawbits, startIndex, n) << (8 - n)); } /** * Packs a bit array into bytes, most significant bit first */ static byte[] convertBoolArrayToByteArray(boolean[] boolArr) { byte[] byteArr = new byte[(boolArr.length + 7) / 8]; for (int i = 0; i < byteArr.length; i++) { byteArr[i] = readByte(boolArr, 8 * i); } return byteArr; } 个对象,您可以使用.isoweekday方法查看星期几,所有工作日都会返回值datetime.date,所以:

<=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)]

因此,您必须制定更多逻辑来确定月份的界限。

要弄清楚每个月的界限,请参阅How to find number of days in the current month

您还可以改进输出的格式化位:

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

更新,现在发布OP的最后一条评论,获取第X个工作日:

如果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] 是9个工作日,则建立在最新的列表comperhansion上:

x

答案 1 :(得分:0)

你想要实现一个基本的算法来解决它,有很多但是这个维基百科文章中列出了一个非常简单的方法:https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week