Home > Software engineering >  What date it was x amount of days ago excluding weekends in Python
What date it was x amount of days ago excluding weekends in Python

Time:08-24

As an example I want to see what the date would be if it was today - 6 days. However, I only want to count days that are weekdays. So given 8/22 the output should be 8/12 as that is 6 business days only.

Tried using the weekday function to return if it is a 5 or 6 for saturday and sunday and skipping those days but I am not having luck so far

Current code:

from datetime import datetime, timedelta

age = 6
counter = 0
difference = datetime.today() - timedelta(counter)

while counter <= age:
difference = datetime.today() - timedelta(counter)
counter = counter   1

this code only returns the day with the weekends included as I haven't been able to figure out how to exclude the weekend. I set up the code to loop to check if it is a 5 or 6 using the weekday() function but I keep getting bad results when attempting that

CodePudding user response:

You can calculate the actual days difference by calculating the number of weekends past, and subtracting the date by the days difference and the days in weekend to get the result.

from datetime import datetime,timedelta
from math import ceil

def subtract_weekdays (from_date, diff): 
    no_of_weekends = ceil((diff - from_date.weekday())/5)
    result_date = from_date - timedelta(days=diff   no_of_weekends * 2)
    return result_date

print subtract_weekdays(datetime.today(), 6)

CodePudding user response:

from datetime import date, timedelta
    

def weekdays_between(startdate,stopdate):
    day = startdate
    daycount = 0
    while day < stopdate :
    if day.weekday() < 5 :
        daycount  = 1
    day = day   timedelta(days=1)
            
    return daycount
        
if __name__ == "__main__" :
    day=date.today()
    dayn=day   timedelta(days=45)
    print(weekdays_between(day,dayn))
    
  • Related