Reputation: 115
I defined a function to create Business date range with custom holiday calendar. I think I got myself into an infinite loop but don't know why?
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
Upvotes: 1
Views: 247
Reputation: 401
Your problem is that you're not incrementing start in your loop if it's a weekday or if it's a holiday. By just using continue
you end up using the same start value indefinitely!
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
To use your earlier example more exactly (although it repeats the start +=
line:
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
Upvotes: 1
Reputation:
From the documentation:
The continue statement, also borrowed from C, continues with the next iteration of the loop:
You need to change your code so that start
is always incremented:
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
Also, do not use list
as a variable name as you will clobber the built-in type.
Upvotes: 1