Recipe 3.3. Calculating Time Periods in a Date Range
Credit: Andrea Cavalcanti
Problem
Given two dates, you want
to calculate the number of weeks between them.
Solution
Once again,
the standard datetime and third-party
dateutil modules (particularly
dateutil's
rrule.count method) come in quite handy. After
importing the appropriate modules, it's a really
simple job:
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( )
Discussion
Function weeks_between takes the starting and ending
dates as arguments, instantiates a rule to recur weekly between them,
and returns the result of the rule's
count methodfaster to code than to
describe. This method will return only an integer (it
won't return
"half" weeks). For example, eight
days is considered two weeks. It's easy to code a
test for this:
if _ _name_ _=='_ _main_ _':This test emits the following output:
starts = [datetime.date(2005, 01, 04), datetime.date(2005, 01, 03)]
end = datetime.date(2005, 01, 10)
for s in starts:
days = rrule.rrule(rrule.DAILY, dtstart=s, until=end).count( )
print "%d days shows as %d weeks "% (days, weeks_between(s, end))
7 days shows as 1 weeksIt's not necessary to give a name to a recurrence
8 days shows as 2 weeks
rule, if you don't want tochanging the
function's body, for example, to the single
statement:
return rrule.rrule(rrule.WEEKLY, dtstart=start_date,works just as well. I prefer to name recurrence rules because
until=end_date).count( )
(frankly) I still find them a bit weird, even though
they're so incredibly useful I doubt I could do
without them!
See Also
Refer to the dateutil module's
documentation available at ,
datetime documentation in the Library
Reference.