Skip to content

Instantly share code, notes, and snippets.

@cuahutli
Last active April 5, 2017 16:06
Show Gist options
  • Save cuahutli/cceca958016f8ecc6546455878bf3810 to your computer and use it in GitHub Desktop.
Save cuahutli/cceca958016f8ecc6546455878bf3810 to your computer and use it in GitHub Desktop.
get week info (number week, first day of week, last day of week) current month and next month
import calendar
from datetime import datetime
def week_of_month(dt):
current_month = (dt.year,dt.month)
next_month = (dt.year +1,1) if dt.month==12 else (dt.year,dt.month + 1)
weeks_month = []
for year,month in [current_month, next_month]:
month_calendar = calendar.monthcalendar(year, month)
week_month = 1
first_day_week = 0
last_day_week = 0
for week in month_calendar:
for day in reversed(week):
if day != 0:
firts_day_week = day
for day in week:
if day != 0:
last_day_week = day
week_dict = dict (year=year, month= calendar.month_name[month], week = week_month, first_day = firts_day_week, last_day = last_day_week)
weeks_month.append(week_dict)
week_month +=1
return weeks_month
if __name__ == "__main__":
weeks = week_of_month(datetime.now())
print (weeks)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment