weekdays in range

Ben Finney ben+python at benfinney.id.au
Sun Oct 18 02:22:29 EDT 2009


Jive Dadson <notontheweb at noisp.com> writes:

> Can someone think of an easy way to calculate the number of weekdays
> between two calendar dates (in Python)?

That depends on what you mean by “weekdays”.

    >>> import datetime
    >>> begin_date = datetime.date(2009, 10, 9)
    >>> end_date = datetime.date(2009, 10, 22)
    >>> import calendar
    >>> print calendar.month(2009, 10)
        October 2009
    Mo Tu We Th Fr Sa Su
              1  2  3  4
     5  6  7  8  9 10 11
    12 13 14 15 16 17 18
    19 20 21 22 23 24 25
    26 27 28 29 30 31
    >>> end_date - begin_date
    datetime.timedelta(13)

If you're expecting to exclude Saturday and Sunday (i.e. if you expect
the above result to be 9 days instead of 13), you can use other
functions of the ‘calendar’ module; try starting with:

    >>> friday_weekday = 4
    >>> len([
    ...     date for date in (
    ...         begin_date + datetime.timedelta(days)
    ...         for days in range((end_date - begin_date).days))
    ...     if calendar.weekday(date.year, date.month, date.day) <= friday_weekday])
    9

-- 
 \       “Selfish, adj. Devoid of consideration for the selfishness of |
  `\          others.” —Ambrose Bierce, _The Devil's Dictionary_, 1906 |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list