Skip to content

Instantly share code, notes, and snippets.

@DavidHickman
Last active July 19, 2016 21:55
Show Gist options
  • Save DavidHickman/bae7ae47d14ca6cb1f9c599885b6e302 to your computer and use it in GitHub Desktop.
Save DavidHickman/bae7ae47d14ca6cb1f9c599885b6e302 to your computer and use it in GitHub Desktop.
Get all dates of a weekday for a month/year. For example, all Tuesdays in July, 2016.
import datetime
import calendar
def get_weekdays_in_month(weekday, month, year):
"""
Calculate a list of all dates of a given weekday in a particular month/year
:param weekday: (str) String of the day of the week
:param month: (int) of the month within the year
:param year: (int) four-digit year
:return: (list) datetime.date objects of the given weekday within a month/year
For example: To get a list of all Tuesdays in July 2016
>>> get_weekdays_in_month('Tuesday', 7, 2016)
[datetime.date(2016, 7, 5), datetime.date(2016, 7, 12), datetime.date(2016, 7, 19), datetime.date(2016, 7, 26)]
"""
selected_dates = []
year_calendar = calendar.Calendar().yeardatescalendar(year, 12)
month_calendar = year_calendar[0][month - 1]
for week in month_calendar:
for day in week:
if day.month == month and weekday.title() == calendar.day_name[day.weekday()]:
selected_dates.append(day)
return selected_dates
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment