Home > Software engineering >  Printing working dates between two dates but excluding every weekends
Printing working dates between two dates but excluding every weekends

Time:03-30

I am trying to print the working days between two dates, but excluding the latter one and the weekends, holding in there. I've tried the following code:

from datetime import timedelta, date, datetime

def print_working_dates(date1, date2):
    excluded = (6,7)
    for n in range(int((date2 - date1).days) 1):
        if date1.isoweekday == excluded:
            continue
        else: 
            yield date1   timedelta(n)
            
start_dt = datetime.now()
end_dt = datetime(2022, 4, 28) 
for dt in print_working_dates(start_dt, end_dt):
    print(dt.strftime("%Y-%m-%d"))

which prints every day before the last one, but it holds all weekends. Could anyone please anyone could give a piece of advice to define better this function? To my mind, the excluded object should be better detailed, but I cannot know how.

CodePudding user response:

Firstly, you can check if a value is in an iterable (such as a tuple or list) using the in keyword. isoweekday is a function, so you need to call it with isoweekday(). Finally, you need to work out the new date, then check it's weekday, otherwise it just checks if the start date is a weekend for every date.

def print_working_dates(date1, date2):
    excluded = (6,7)
    for n in range(int((date2 - date1).days) 1):
        new = date1   timedelta(n)
        if new.isoweekday() not in excluded:
            yield new

I've negated the if statement with not to make it a bit more compact.

CodePudding user response:

First off, you are not checking the correct time to be a weekday or not you have to check if (date1 timedelta(n)) is a weekday, not date1

And secondly you have to you have to check if isoweekday's return value is in the excluded

Here's my solution to your code:

from datetime import timedelta, datetime

def print_working_dates(date1, date2):
excluded = (6,7)
for n in range(int((date2 - date1).days) 1):
    if (date1   timedelta(n)).isoweekday() in excluded:
        continue
    else: 
        yield date1   timedelta(n)
        
start_dt = datetime.now()
end_dt = datetime(2022, 4, 28) 
for dt in print_working_dates(start_dt, end_dt):
print(dt.strftime("%Y-%m-%d"))
  • Related