日历功能也在月底停止

时间:2016-11-17 13:12:48

标签: python

我有这个python函数:

import datetime
def date_by_adding_business_days(from_date, add_days,holidays):
    business_days_to_add = add_days
    current_date = from_date
    while business_days_to_add > 0:
        current_date += datetime.timedelta(days=1)
        weekday = current_date.weekday()
        if weekday >= 5:
            continue
        if current_date in holidays:
            continue
        business_days_to_add -= 1
    return current_date
Holidays =[datetime.datetime(2015,10,3),datetime.datetime(2015,10,4)]
print date_by_adding_business_days(datetime.date(2015,10,23), 6,Holidays)

这将输出:

2015-11-02

我想要的是做出一个更改,输出日期将在月末停止,因为我的例子我需要输出2015-10-30。对于任何给定日期,我不希望输出超出给定日期月份。如果我会说:datetime.date(2015,10,29)并且我想要添加5天,这应该输出2015-10-30(仅添加1天),依此类推。假期(在我的清单中标明)和周末不计算在内。

enter image description here

谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用返回元组(first weekday of month, days in month)的{​​{3}}来确定给定月份的天数:

>>> import calendar
>>> calendar.monthrange(2015, 10)
(3, 31)

然后,您可以更改函数,以便在每次到达循环结束时存储潜在结果。最重要的是,您需要将holidays的类型更改为date而不是datetime,因为它们是不同的对象:

>>> import datetime
>>> datetime.datetime(2016, 11, 17) == datetime.date(2016, 11, 17)
False

通过以上更改,最终结果将如下所示:

import datetime
import calendar

def date_by_adding_business_days(from_date, add_days,holidays):
    business_days_to_add = add_days
    current_date = from_date
    result = None
    _, days_in_month = calendar.monthrange(current_date.year, current_date.month)
    while business_days_to_add > 0 and current_date.day < days_in_month:
        current_date += datetime.timedelta(days=1)
        weekday = current_date.weekday()
        if weekday >= 5:
            continue
        if current_date in holidays:
            continue
        business_days_to_add -= 1
        result = current_date
    return result
Holidays =[datetime.date(2015,10,3),datetime.date(2015,10,4)]
print date_by_adding_business_days(datetime.date(2015,10,23), 6,Holidays)

输出:

2015-10-30