-3

I am working on something to automatically get the last day of class, depending on the first day and days of school.

I am struggling to find a way to skip off days and automatically add +1 day to have the correct end date. Also of course, if last day falls on a week-end, it should continue until it falls on a weekday.

Here's my code so far :

start_date = datetime.date(2019, 9, 30)
number_of_days = 5

date_list = []
for day in range(number_of_days):
    a_date = (start_date + datetime.timedelta(days = day)).isoformat()
    date_list.append(a_date)

print(date_list[-1])

I was thinking of putting all of my off days in a separate list, and iterate on it, but I cant find a way to add +1 in datetime. Also, creating a list of date seems difficult, as you can't iterate on dates?

1 Answers1

1

you could simply iterate through the days one at a time and discard those on weekends and in the "off-days" list until you have enough class days

import datetime

start_date = datetime.date(2019, 9, 30)
number_of_days = 5

off_days = (
    datetime.date(2019, 10, 1),
)

days_of_class = [start_date]
day = start_date
while len(days_of_class) < number_of_days:
    day = day + datetime.timedelta(days=1)
    if day.isoweekday() in (6, 7):  
        # saturday, sunday
        continue
    if day in off_days:
        continue
    days_of_class.append(day)

print(days_of_class)
Sebastian Loehner
  • 1,302
  • 7
  • 5