Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Given a Date and Weekday find the date of the next occurrence of a given weekday

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.

like image 399
Jon Avatar asked Jan 03 '12 04:01

Jon


1 Answers

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
like image 59
eumiro Avatar answered Oct 21 '22 17:10

eumiro