Newbie
Newbie

Reputation: 146

Calculate no of whole weeks for a given dates

from datetime import datetime

def calculate_whole_week(year, start_month, end_month, weekday):
    date_str_start =  str(year)+' ' + start_month+' '+ weekday
    date_str_end =  str(year)+' ' + end_month+' '+ weekday
    start_day = datetime.strptime(date_str_start, '%Y %B %A')  
    end_day = datetime.strptime(date_str_end, '%Y %B %A')
    no_of_whole_weeks =  (end_day - start_day).days//7 -1
    return no_of_whole_weeks


calculate_whole_week(2014,'April','May','Wednesday')

I tried the following but I am unable to compile it

start_week_day = time.strptime(str(Y)+' '+ A + ' '+ W,"%Y %B %A").tm_wday
end_week_day = time.strptime(str(Y)+' '+ B + ' '+ W,"%Y %B %A").tm_wday

start_dt = time.strptime(str(Y)+' '+A+' '+ str(start_week_day),'%Y %B %d')
end_dt = time.strptime(str(Y)+' '+ B +' '+ str(end_week_day),'%Y %B %d')
no_of_whole_weeks =  (end_dt - start_dt).days//7 -1
print (end_dt - start_dt).days
return no_of_whole_weeks

The challenge I am facing here is how do I calculate the exact date for weekday I pass

If I run the above code I get 3 instead of 7

Upvotes: 0

Views: 1335

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122154

Why don't you break the problem up into smaller chunks, and tackle each one separately? For example:

  1. Given two date or datetime objects, determine the number of whole weeks between them:

    def whole_weeks(start, end):
        """Number of whole weeks between start and end dates."""
        weeks = 0
        while start <= end:
            start += datetime.timedelta(weeks=1)
            weeks += 1
        return weeks - 1
    
  2. Given a year, month name and weekday name, calculate the first date matching it:

    def first_matching_date(year, month_name, weekday_name):
        """The first date a weekday occurred in a given month and year."""
        day = datetime.datetime.strptime(str(year) + month_name, '%Y%B')
        for _ in range(7):
            if day.strftime('%A') == weekday_name:
                return day
            day += datetime.timedelta(days=1)
        raise ValueError('no matching date for {!r}'.format(weekday_name))
    
  3. Therefore, given a year, two months and a weekday, find the number of whole weeks between the first occurrence of that weekday in each month:

    def calculate_whole_week(year, start_month, end_month, weekday_name):
        """Whole weeks between the weekday in specified start and end month."""
        return whole_weeks(
            first_matching_date(year, start_month, weekday_name),
            first_matching_date(year, end_month, weekday_name),
        )
    

This makes it so much easier to develop and test each step, leads to more readable code and gives me:

>>> calculate_whole_week(2014, 'April', 'May', 'Wednesday')
5

which is indeed the number of whole weeks between the first Wednesday in April 2014 (2014/4/2) and the first Wednesday in May 2014 (2014/5/7); I'm not sure why you expected 7. I may have misunderstood the specific problem, but hopefully you can take the process of decomposing it and apply it to your actual task.

Upvotes: 2

Related Questions