Adding days to a given date (Consider working days only)
-
Some times, we may be getting requirements like finding the 10th working day from today. Most common scenarios are for sending email reminders considering only business days. For this we will have to add days to a particular date, excluding weekends.
To add only working days to a date, we have to identify the Saturdays and Sundays within the range using strftime('%w') function. This functions returns weekday numbers. For Sunday, the number returned is 0 and for Saturday it is 6. Then using a while loop we can check each day within the range for weekends and skip those.
Code sample provided below. -
Copied
import datetime def findWorkingDayAfter (startDate, daysToAdd): #0 - Sunday and 6 Saturday are to be skipped workingDayCount = 0 while workingDayCount < daysToAdd: startDate += datetime.timedelta(days=1) weekday = int(startDate.strftime('%w')) if (weekday != 0 and weekday != 6): workingDayCount += 1 return startDate startDate = datetime.datetime(2022, 1, 15) daysToAdd = 10 print(findWorkingDayAfter(startDate, daysToAdd))
On running the above sample we will get the below output.
Output:
2022-01-28 00:00:00 -
By slightly modifying the above function, we can add logic to skip holidays list also. Keep list of holidays in a tuple in the format (month, day). Then add an additional check to exclude those values.
Note that startDate.strftime('%m') and startDate.strftime('%d') return the values padded with a 0. So the list should also have padded numbers as in sample below.
-
Copied
import datetime def findWorkingDayAfter (startDate, daysToAdd): #0 - Sunday and 6 Saturday are to be skipped workingDayCount = 0 holidays = ( '01-20', '01-23', '02-15', '03-01' ) while workingDayCount < daysToAdd: startDate += datetime.timedelta(days=1) weekday = int(startDate.strftime('%w')) if (weekday != 0 and weekday != 6): currentday = str(startDate.strftime('%m')) + '-' + str(startDate.strftime('%d')) if(not(any( currentday in day for day in holidays))): workingDayCount += 1 return startDate startDate = datetime.datetime(2022, 1, 15) daysToAdd = 10 print(findWorkingDayAfter(startDate, daysToAdd))
On running the above sample we will get the output.
Output:
2022-01-31 00:00:00We have marked 20 and 23 of January as holidays. Since 23 is already a weekend, only 20 is skipped from the first example and we get the output as 31-Jan-2022 (29 and 30 are weekends).