How to find number of Mondays or any other weekday between two dates in Python?

You can define a function and use it like this :

def num_days_between( start, end, week_day):
    num_weeks, remainder = divmod( (end-start).days, 7)
    if ( week_day - start.weekday() ) % 7 < remainder:
       return num_weeks + 1
    else:
       return num_weeks

where week_day is day number you wan to calculate count.


This code still uses a for loop and an if/else.

import datetime
import calendar

def weekday_count(start, end):
  start_date  = datetime.datetime.strptime(start, '%d/%m/%Y')
  end_date    = datetime.datetime.strptime(end, '%d/%m/%Y')
  week        = {}
  for i in range((end_date - start_date).days):
    day       = calendar.day_name[(start_date + datetime.timedelta(days=i+1)).weekday()]
    week[day] = week[day] + 1 if day in week else 1
  return week

print(weekday_count("01/01/2017", "31/01/2017"))

# prints result
# {'Monday': 5, 'Tuesday': 5, 'Friday': 4, 'Wednesday': 4, 'Thursday': 4, 'Sunday': 5, 'Saturday': 4}