在给定的日期添加n个工作日,忽略假日和周末在python [英] Add n business days to a given date ignoring holidays and weekends in python

查看:220
本文介绍了在给定的日期添加n个工作日,忽略假日和周末在python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在给定日期添加n(整数)个工作日,添加日期必须避免假期和周末(在工作日内不包括)

I'm trying to add n (integer) working days to a given date, the date addition has to avoid the holidays and weekends (it's not included in the working days)

推荐答案

跳过周末将很容易做这样的事情:

Skipping weekends would be pretty easy doing something like this:

import datetime
def date_by_adding_business_days(from_date, add_days):
    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: # sunday = 6
            continue
        business_days_to_add -= 1
    return current_date

#demo:
print '10 business days from today:'
print date_by_adding_business_days(datetime.date.today(), 10)

假期的问题是它们因国家或地区,宗教信仰而异等等。您将需要一个用于您的用例的列表/一组假期,然后以类似的方式跳过它们。一个起点可能是苹果为iCal(以ics格式)发布的日历Feed,美国的日期Feed将为 http://files.apple.com/calendars/US32Holidays.ics

The problem with holidays is that they vary a lot by country or even by region, religion, etc. You would need a list/set of holidays for your use case and then skip them in a similar way. A starting point may be the calendar feed that Apple publishes for iCal (in the ics format), the one for the US would be http://files.apple.com/calendars/US32Holidays.ics

您可以使用 icalendar 模块来解析这个。

You could use the icalendar module to parse this.

这篇关于在给定的日期添加n个工作日,忽略假日和周末在python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆