计算给定日期的整周数

时间:2015-08-19 15:27:43

标签: python weekday

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')

我尝试了以下但我无法编译它

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

我在这里面临的挑战是如何计算我通过的工作日的确切日期

如果我运行上面的代码,我会得到3而不是7

1 个答案:

答案 0 :(得分:2)

为什么不将问题分解成更小的块,并分别处理每个问题?例如:

  1. 鉴于两个datedatetime个对象,请确定它们之间的整周数:

    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. 给定年份,月份名称和工作日名称,计算与之匹配的第一个日期:

    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. 因此,给定一年,两个月和一个工作日,找出每个工作日第一次出现的整周数:

    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),
        )
    
  4. 这使得更容易来开发和测试每一步,从而产生更易读的代码并给我:

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

    这确实是2014年4月第一个星期三(2014/4/2)和2014年5月第一个星期三(2014/5/7)之间的整周数;我不确定你为什么期待7。我可能误解了具体问题,但希望您可以将进程分解并将其应用到您的实际任务中。