views:

424

answers:

2

Hello, I need to subtract business days from the current date.

I currently have some code which needs always to be running on the most recent business day. So that may be today if we're Monday thru Friday, but if it's Saturday or Sunday then I need to set it back to the Friday before the weekend. I currently have some pretty clunky code to do this:

 lastBusDay = datetime.datetime.today()
 if datetime.date.weekday(lastBusDay) == 5:      #if it's Saturday
     lastBusDay = lastBusDay - datetime.timedelta(days = 1) #then make it Friday
 elif datetime.date.weekday(lastBusDay) == 6:      #if it's Sunday
     lastBusDay = lastBusDay - datetime.timedelta(days = 2); #then make it Friday

Is there a better way?

Can I tell timedelta to work in weekdays rather than calendar days for example?

+2  A: 

Here's a snippet from dzzone that might help you out: http://snippets.dzone.com/posts/show/9173

David Underhill
thanks dound yes full blown solution but actually I just wanted to know if there's something quicker already built into datetime.
Thomas Browne
Fair enough :). Glad you found what you needed.
David Underhill
+3  A: 

There seem to be several options if you're open to installing extra libraries.

This post describes a way of defining workdays with dateutil.

http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-09/3758.html

BusinessHours lets you custom-define your list of holidays, etc., to define when your working hours (and by extension working days) are.

http://pypi.python.org/pypi/BusinessHours/

Alison R.
nice one Alison. Still not very simple though unfortunately. I'm going to go your route though. Thanks for the help.
Thomas Browne
Defining business days across all cultures is unlikely to be simple enough a problem to get included in the standard library.
Alison R.
A valid point, as indeed my application is for financial markets, and Egypt and Israel are open on Sunday.
Thomas Browne