Python: How to render a Calendar month (including days from surrounding months)

It's nice to have a calendar that displays all the days in a month, but sometimes its handy to also display the extra days padding the month so you don't end up with blank spots.

image image
Left has no padding. Right has padding dates in grey.

I like to have more information when possible. So, to get those extra days you just have to use a simple method already built into the calendar system.

from calendar import Calendar, SUNDAY def generate_date_range(year, month): # Process the calendar month to get the proper start/end dates
cal = Calendar(SUNDAY) # Make Sunday first day of the week
days = [ day for day in cal.itermonthdates(year, month) ]
return days

Another thing you may find helpful is to split the days into weeks for display in rows.

def split_days_to_weeks(days):
weeks = []

for i in range((len(days) / 7) +1):
weeks.append(days[i * 7 : (i+1) * 7])

return weeks

[ Source ]

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog