python - 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 following unable compile it

start_week_day = time.strptime(str(y)+' '+ + ' '+ 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 facing here how calculate exact date weekday pass

if run above code 3 instead of 7

why don't break problem smaller chunks, , tackle each 1 separately? example:

  1. given 2 date or datetime objects, determine number of whole weeks between them:

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

    def first_matching_date(year, month_name, weekday_name):     """the first date weekday occurred in given month , year."""     day = datetime.datetime.strptime(str(year) + month_name, '%y%b')     _ in range(7):         if day.strftime('%a') == weekday_name:             return day         day += datetime.timedelta(days=1)     raise valueerror('no matching date {!r}'.format(weekday_name)) 
  3. therefore, given year, 2 months , weekday, find number of whole weeks between first occurrence of weekday in each month:

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

this makes so easier develop , test each step, leads more readable code , gives me:

>>> calculate_whole_week(2014, 'april', 'may', 'wednesday') 5 

which indeed number of whole weeks between first wednesday in april 2014 (2014/4/2) , first wednesday in may 2014 (2014/5/7); i'm not sure why expected 7. may have misunderstood specific problem, can take process of decomposing , apply actual task.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -