Python Cookbook 2Nd Edition Jun 1002005 [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Python Cookbook 2Nd Edition Jun 1002005 [Electronic resources] - نسخه متنی

David Ascher, Alex Martelli, Anna Ravenscroft

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید


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 ,
datetime documentation in the Library
Reference
.

/ 394