自定义Python获得BDay范围

时间:2017-04-11 20:12:42

标签: python datetime

我定义了一个功能,用自定义假日日历创建营业日期范围。我想我已陷入无限循环,但不知道为什么?

import datetime as dt

def get_bdate(start, end, hoildays):
list = []
while  start < end:
    if start.weekday() >= 5: # sunday = 6; skipping weekends
        continue
    if start in holidays: # holidays is a custom set of dates
        continue
    list.append(start)
    start += dt.timedelta(days=1)
return list

2 个答案:

答案 0 :(得分:1)

来自documentation

  

continue语句也是从C借用的,继续循环的下一次迭代:

您需要更改代码,以便import datetime as dt def get_bdate(start, end, holidays): result = list() while start < end: if start.weekday() >= 5: # sunday = 6; skipping weekends pass elif start in holidays: # holidays is a custom set of dates pass else: result.append(start) start += dt.timedelta(days=1) return result 始终递增:

list

此外,请勿使用std::map<int, std::thread>作为变量名称,因为您将破坏built-in type

答案 1 :(得分:1)

你的问题是,如果是工作日或者假期,你就不会在循环中增加开始。只需使用continue,您就会无限期地使用相同的起始值!

import datetime as dt

def get_bdate(start, end, hoildays):
    my_list = []
    while  start < end:
        if start.weekday() > 5 or start not in holidays: 
            my_list.append(start)
        start += dt.timedelta(days=1)
    return my_list

更准确地使用您之前的示例(尽管它会重复start +=行:

import datetime as dt

def get_bdate(start, end, hoildays):
    my_list = []
    while  start < end:
        if start.weekday() >= 5: # sunday = 6; skipping weekends
            start += dt.timedelta(days=1)
            continue
        if start in holidays: # holidays is a custom set of dates
            start += dt.timedelta(days=1)
            continue
        my_list.append(start)
        start += dt.timedelta(days=1)
    return my_list