This is a bit difficult to explain, so I apologize if this doesn't make much sense.
I have a program where I am doing some scheduling. One of the settings it has is to run a task weekly on certain days. For example, weekly on Monday, Wednesday and Friday.
Consider the example where the current task is scheduled for 1/2/2012, which is a Monday, I already have a bunch of code working to the point where I know the next task run should be on the wednesday following 1/2/2012. All I need to do is calculate the actual date of that Wednesday (1/4/2012).
I actually have the day of the week as the corresponding integer from date.weekday(), so in this case I have 2 which represents wednesday.
Whats the best way to handle something like this? I feel like there should be a fairly simple solution, but it isn't coming to mind. I was thinking of using a calendar object to search through to find the day of the week I want, but that seems like overkill.
Use dateutil.relativedelta:
from dateutil import relativedelta
import datetime
today = datetime.date.today()
# datetime.date(2012, 1, 3)
today + relativedelta.relativedelta(weekday=2) # 2 is Wednesday
# datetime.date(2012, 1, 4)
today + relativedelta.relativedelta(weekday=6) # 6 is Sunday
# datetime.date(2012, 1, 8)
today + relativedelta.relativedelta(weekday=1) # 1 is Tuesday
# datetime.date(2012, 1, 3)
# returns today
today + relativedelta.relativedelta(weeks=1, weekday=1)
# datetime.date(2012, 1, 10)
# returns Tuesday at least one week ahead
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With