How to calculate difference between two dates in weeks in python
This is a very simple solution with less coding everyone would understand.
from datetime import date
d1 = date(year, month, day)
d2 = date(year, month, day)
result = (d1-d2).days//7
You may want to refer the Python CookBook (2005 edition) Recipe 3.3. The following code snippet is from the cookbook, does what you require.
from dateutil import rrule
import datetime
def weeks_between(start_date, end_date):
weeks = rrule.rrule(rrule.WEEKLY, dtstart=start_date, until=end_date)
return weeks.count()
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.