How to find number of whole weeks between dates?

Ian Kelly ian.g.kelly at gmail.com
Wed Jun 10 23:45:32 EDT 2015


On Wed, Jun 10, 2015 at 9:19 PM, Michael Torrie <torriem at gmail.com> wrote:
> On 06/10/2015 02:11 PM, Sebastian M Cheung via Python-list wrote:
>> On Wednesday, June 10, 2015 at 6:06:09 PM UTC+1, Sebastian M Cheung wrote:
>>> Say in 2014 April to May whole weeks would be 7th, 14th 28th April and  May would be 5th, 12th and 19th. So expecting 7 whole weeks in total
>>
>> What I mean is given two dates I want to find WHOLE weeks, so if given the 2014 calendar and function has two inputs (4th and 5th month) then 7th, 14th, 21st and 28th from April with 28th April week carrying into May, and then 5th, 12th and 19th May to give total of 7 whole weeks, because 26th May is not a whole week and will not be counted.
>>
>> Hope thats clear.
>
> I think Joel had the right idea.  First calculate the rough number of
> weeks by taking the number of days between the date and divide by seven.
> Then check to see what the start date's day of week is, and adjust the
> rough week count down by one if it's not the first day of the week.  I'm
> not sure if you have to check the end date's day of week or not.  I kind
> of think checking the first one only is sufficient, but I could be
> wrong.  You'll have to code it up and test it, which I assume you've
> been doing up to this point, even though you haven't shared any code.

I don't think the logic is quite right. Consider:

>>> cal = calendar.TextCalendar()
>>> print(cal.formatmonth(2014, 6))
     June 2014
Mo Tu We Th Fr Sa Su
                   1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30

>>> date(2014, 7, 1) - date(2014, 6, 1)
datetime.timedelta(30)
>>> _.days // 7 - 1
3



More information about the Python-list mailing list