How to calculate difference between two dates in weeks in python

How about calculating the difference in weeks between the Mondays within weeks of respective dates? In the following code, monday1 is the Monday on or before d1 (the same week):

from datetime import datetime, timedelta

monday1 = (d1 - timedelta(days=d1.weekday()))
monday2 = (d2 - timedelta(days=d2.weekday()))

print 'Weeks:', (monday2 - monday1).days / 7

Returns 0 if both dates fall withing one week, 1 if on two consecutive weeks, etc.

Leave a Comment