【问题标题】:How would you get the xth weekday of a given month in python?你如何在 python 中获得给定月份的第 x 个工作日?
【发布时间】:2016-05-19 09:04:00
【问题描述】:

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

对不起,如果以前有人问过这个问题!在 python 中似乎找不到解决方案。

【问题讨论】:

  • 抱歉,什么是工作日?不清楚你想要什么,5 月 10 日,或者你想要星期几的名字,例如星期一?
  • 啊,应该更清楚了。所以,我不想要 5 月 10 日。但我希望该函数返回一个日期时间,即 5 月的第 10 天,不包括周末。

标签: python datetime


【解决方案1】:

给定一个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

【讨论】:

  • 你也可以。但如果您不关心或不了解 ISO 标准的细节,我觉得它更具可读性。 _days_in_month!太棒了!
  • 哦等等...del (... _days_in_month, ...) .....该死>:(只有在_datetime无法加载C实现时才可用。
  • 似乎也只有 Python3 中的 datetime.py
  • 但它在日历中可用
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2012-10-19
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多