O'Reilly logo

Python Cookbook, 2nd Edition by David Ascher, Anna Ravenscroft, Alex Martelli

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.6. Looking up Holidays Automatically

Credit: Anna Martelli Ravenscroft, Alex Martelli

Problem

Holidays vary by country, by region, even by union within the same company. You want an automatic way to determine the number of holidays that fall between two given dates.

Solution

Between two dates, there may be movable holidays, such as Easter and Labor Day (U.S.); holidays that are based on Easter, such as Boxing Day; holidays with a fixed date, such as Christmas; holidays that your company has designated (the CEO's birthday). You can deal with all of them using datetime and the third-party module dateutil.

A very flexible architecture is to factor out the various possibilities into separate functions to be called as appropriate:

import datetime from dateutil import rrule, easter try: set except NameError: from sets import Set as set def all_easter(start, end): # return the list of Easter dates within start..end easters = [easter.easter(y) for y in xrange(start.year, end.year+1)] return [d for d in easters if start<=d<=end] def all_boxing(start, end): # return the list of Boxing Day dates within start..end one_day = datetime.timedelta(days=1) boxings = [easter.easter(y)+one_day for y in xrange(start.year, end.year+1)] return [d for d in boxings if start<=d<=end] def all_christmas(start, end): # return the list of Christmas Day dates within start..end christmases = [datetime.date(y, 12, 25) for y in xrange(start.year, end.year+1)] return [d for d in christmases if start<=d<=end] def all_labor(start, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required