Skip to content

Instantly share code, notes, and snippets.

@tuxskar
Created September 14, 2016 07:27
Show Gist options
  • Save tuxskar/a2977e87cbfa3f30cc5ad0ccee726751 to your computer and use it in GitHub Desktop.
Save tuxskar/a2977e87cbfa3f30cc5ad0ccee726751 to your computer and use it in GitHub Desktop.
Passing as arguments the first day (first_date), the number of weeks between events (k), the days of the week (days_of_the_week) and the number of next event requested (n) will answer with the n next appointment dates
import datetime
FORMAT = '%d/%m/%Y'
def next_weekday(d, weekday):
days_ahead = weekday - d.weekday()
if days_ahead <= 0: # Target day already happened this week
days_ahead += 7
return d + datetime.timedelta(days_ahead)
def recurring_task(first_date, k, days_of_the_week, n):
fd = datetime.datetime.strptime(first_date, FORMAT)
weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
# get the first day of each days_of_the_week
out = []
fd -= datetime.timedelta(days=1)
for day in days_of_the_week:
next_day = weekdays.index(day)
next_fd = next_weekday(fd, next_day)
# build a list of next events for each day of the week
# getting enough elements for the next elements
for i in range((n / len(days_of_the_week)) + 1):
next_fd_with_k = next_fd + datetime.timedelta(i * k * 7)
out.append(next_fd_with_k)
# collect the generated information and sort it
out.sort()
return map(lambda x: x.strftime(FORMAT), out[:n])
def test():
assert recurring_task('01/01/2015', 2, ["Monday", "Thursday"], 4) == ["01/01/2015", "05/01/2015",
"15/01/2015", "19/01/2015"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment