A function to check number of weekends between two days in the Calendar module

Finding the number of weekdays between two dates can be a handy metric. Further enhancements can be done by including a user-defined list of holidays in the arguments(I have mentioned that as comments).

def get_weekends_count(start_date , end_date):
   #find the number of weekends between start_date and end_date
           start_date_weekday = start_date.weekday()
           end_date_weekday = end_date.weekday()
           first_day_of_week_dayoftheweek = start_date_weekday
           total_days = (end_date - start_date).days + 1 #caution

           div = int(total_days / 7)
           rem = int(total_days % 7)

           num_weekends = div * 2
           for i in range(rem):
               if(first_day_of_week_dayoftheweek + i) % 7 in (5,6):
                   num_weekends += 1

           # print("WEEKENDS NO.",num_weekends)
           num_weekdays = (total_days - num_weekends)
           # print("WEEKDAYS NO.", num_weekdays)

           # # Exclude holidays from weekdays
           # for holiday in holidays:
           #     if start_date <= holiday <= end_date and holiday.weekday() not in (5, 6):
           #         num_weekdays -= 1

           return num_weekends```

Depending on what you want to count exactly, the functionality is already available in numpy: numpy.busday_count — NumPy v1.26 Manual

divmod comes in handy here:

           div, rem = divmod(total_days, 7)
1 Like

I wanted to see if it was a good idea to implement it from scratch using Math, without using any pre-defined functionalities.

A bit of off-topic here, but I’ve never ever thought NumPy would contain a function for this kind of computation :o