Two related issues: (1) All of the data I work with have weekday dates attached. At various points, I need to know what the next weekday is. I've written something like the code below to make this determination, but I'm sure there's a better way. Anyone? (2) Ideally, I need to know not just the next weekday, but the next US business day--that is, the next weekday that is not a US market holiday. Any help on this would also be great.
import datetime as dt
day = dt.datetime.strptime('2012-02-03','%Y-%m-%d').date()
print day#day=2012-03-02 (Friday)
if day.weekday()==4:
day = day+dt.timedelta(days=3)
else:
day = day+dt.timedelta(days=1)
print day#day=2012-02-06 (Monday)
day = day+dt.timedelta(days=1)
print day#day=2012-02-07 (Tuesday)
解决方案import datetime
from dateutil import rrule
holidays = [
datetime.date(2012, 5, 1,),
datetime.date(2012, 6, 1,),
# ...
]
# Create a rule to recur every weekday starting today
r = rrule.rrule(rrule.DAILY,
byweekday=[rrule.MO, rrule.TU, rrule.WE, rrule.TH, rrule.FR],
dtstart=datetime.date.today())
# Create a rruleset
rs = rrule.rruleset()
# Attach our rrule to it
rs.rrule(r)
# Add holidays as exclusion days
for exdate in holidays:
rs.exdate(exdate)
print rs[0]