How to find number of whole weeks between dates?

Chris Angelico rosuav at gmail.com
Wed Jun 10 23:36:15 EDT 2015


On Thu, Jun 11, 2015 at 1:19 PM, Michael Torrie <torriem at gmail.com> wrote:
> 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.

Alternatively, you could start by rounding the start date up to the
next week boundary, then round the end date down to the previous week
boundary, and then calculate from there. Something like this:

>>> start = datetime.date(2015, 1, 4)
>>> end = datetime.date(2015, 4, 2)
>>> start += datetime.timedelta(7-start.isoweekday())
>>> end -= datetime.timedelta(end.isoweekday() % 7)

Now both dates represent Sundays. If either already did, it hasn't been changed.

>>> (end - start).days//7
12

There are twelve complete Sunday-to-Sunday weeks (plus any loose days
either end) between the original dates.

Depending on your definition of "complete week", you may need to
adjust this code some.

ChrisA



More information about the Python-list mailing list