Calculating days using Business Days for the Calendar
Anna Martelli Ravenscroft
anna at aleax.it
Mon Sep 20 17:58:41 EDT 2004
David Stockwell wrote:
> I''m wondering if the Calendar object has an option to only do
> calculations based on business days (ie M-F). Additionally does it have
> a way to get holidays into itself?
>
> Currently I'm considering converting my calculations over to business
> days and am wondering if there is anything built-in. I've tried
> searching but so far haven't seen such a thing built in.
>
> I'm thinking I'm just going to have to bite the bullet and create my own
> approach to
> 1) figure out the day of the week of my starting date
> (Calendar.weekday() should do the trick)
> 2) determine the number of days up to my finish date (i do that now)
> 3) determine the number of non-business days (weekends + holidays)
> 4) subtract off the number in #3 from #2
AFAIK - there is no built-in to calculate this. Part of the problem may
be that the European work week often includes Saturdays.
I created my own - in fact, that was my very first Python program. (That
was before the new datetime and dateutil modules.) I've long since lost
that script (left it on my work computer), but there's better ways to do
it now anyway.
Some notes on rolling your own:
Be careful on determining the number of days in your step (2) above -
you can easily end up with off-by-one errors.
Also, you'll need to set up your own list (or dict) of holidays - they
vary by region (and by union). I created a script for that so I could
add to it, pickled it and imported it at need.
dateutil is great and the documentation is pretty kewl - but has an
unfortunate tendency toward "from module import *"... Other than that,
it's a really kewl module - be sure to check out the date parser.
Here's a snippet of code that does the job but would need to be prettied up:
import datetime
from dateutil import rrule
alpha=datetime.date(2004, 01, 01) # change to accept input
omega=datetime.date(2004, 02, 01) # change to accept input
dates=rrule.rruleset() # create an rrule.rruleset instance
dates.rrule(rrule.rrule(rrule.FREQ_DAILY, dtstart=alpha, until=omega))
# this set is INCLUSIVE of alpha and omega
dates.exrule(rrule.rrule(rrule.FREQ_DAILY,
byweekday=(rrule.SA, rrule.SU),
dtstart=alpha))
# here's where we exclude the weekend dates
print len(list(dates)) # there's probably a faster way to handle this
HTH
Anna
More information about the Python-list
mailing list