@Ankit, here is brute-force version:
from datetime import datetime, date, timedelta
date_start = datetime.strptime('2015-01-01','%Y-%m-%d').date()
date_end = datetime.strptime('2015-03-31','%Y-%m-%d').date()
delta_day = timedelta(days=1)
days = {'mon':0,'tue':1,'wed':2,'thu':3,'fri':4,'sat':5,'sun':6}
dt = date_start
day_count=0
while dt <= date_end:
if dt.weekday() != days['tue']:
day_count+=1
dt += delta_day
But suggestion of @Drees is much more lightweight and should be executed faster for large periods, if you'll get it worked.
UPDATE:
slightly modified approach suggested by @Drees, if we make sure day count starts at the weekday we are interested in (by "removing" days before first occurrence of the target day i.e. weekday to be excluded), then total count of weekday occurrence will be:
# total_days -- days between start_date (inclusive) and and_date (inclusive)
# days_before -- days from total_days period, that are before first occurrence of the weekday to be excluded
weekday_count = (total_days - days_before) / 7
if (total_days - days_before) % 7:
weekday_count = weekday_count + 1
days_wit_excluded_target_day = total_days - weekday_count
If we're agree that above code may calculate correctly the day count in [start_date, end_date] period with a target_weekday excluded, then there is a corresponding code:
version with calculation
from datetime import datetime
date_start_val = '2015-01-01' # start date (inclusive)
date_end_val = '2015-03-31' # end date (inclusive)
date_start = datetime.strptime(date_start_val,'%Y-%m-%d').date()
date_end = datetime.strptime(date_end_val,'%Y-%m-%d').date()
days = {'mon':0,'tue':1,'wed':2,'thu':3,'fri':4,'sat':5,'sun':6}
total_days = (date_end - date_start).days + 1
first_weekday = date_start.weekday()
target_weekday = days['tue']
if target_weekday == first_weekday:
days_before = 0
elif target_weekday < first_weekday:
days_before = 7 - first_weekday + target_weekday
else:
days_before = target_weekday - first_weekday
weekday_count = total_days - days_before
if weekday_count > 0:
weekday_count = weekday_count/7 + (weekday_count%7 and 1 or 0)
else:
weekday_count = 0
day_count = total_days - weekday_count
this version should be much faster on large periods then other versions.