Recipe3.3.Calculating Time Periods in a Date Range


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_ _':     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))

This test emits the following output:

7 days shows as 1 weeks 8 days shows as 2 weeks

It's not necessary to give a name to a recurrence 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, until=end_date).count( )

works just as well. I prefer to name recurrence rules because (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 https://moin.conectiva.com.br/DateUtil?action=highlight&value=DateUtil, datetime documentation in the Library Reference.



Python Cookbook
Python Cookbook
ISBN: 0596007973
EAN: 2147483647
Year: 2004
Pages: 420

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net