Counting weekdays between dates

Need a method to accurately count the number of weekdays between two days?  [The key here is "accurately", it is a bit harder than it seems at first].  In Python there are several ways to do this, but most involve some iteration or list comprehension.  In my opinion, if you have to do that, you are probably violating the Python idiom of "use the batteries".
A better way to solve this is to use recurrence rules - used every day in scheduling software, groupware, and anything that supports iCalendar.  Recurrence rules in Python are handled by the dateutil module's rrule component.  Here is the code:

from datetime import date, timedelta
from dateutil.rrule import rrule, MO, TU, WE, TH, FR, DAILY
start = date.today( ) - timedelta( days=90 )
end = date.today( ) + timedelta( days=3 )
rule = rrule( DAILY,
              byweekday=( MO, TU, WE, TH, FR ),
              until=end )
print( 'Days: {0}'.format( rule.count( ) )

The date range here is inclusive, it includes both the start and end dates.  One caveat is that if your end date is prior to the start date you will not get an error or exception - you'll just get a recurrence with zero elements.

No comments:

Post a Comment