import datetime import calendar class MonthCalendarMatrix(object): def __init__(self, year, month, weeksPerRow, fixedRows=True): self.weeksPerRow = weeksPerRow self.firstDayInMonth = datetime.date(year,month,1) maxDay = calendar.monthrange(self.firstDayInMonth.year, self.firstDayInMonth.month)[1] self.lastDayInMonth = datetime.date(self.firstDayInMonth.year, self.firstDayInMonth.month, maxDay) self.firstDayInMonth = self.firstDayInMonth - datetime.timedelta(days=self.firstDayInMonth.weekday()) self.lastDayInMonth = self.lastDayInMonth + datetime.timedelta(days=(6-self.lastDayInMonth.weekday())) self.numDays = (self.lastDayInMonth - self.firstDayInMonth + datetime.timedelta(days=1)).days self.numRows = int(self.numDays / ( 7 * self.weeksPerRow )) if fixedRows: if ( self.numRows < ( 6 / self.weeksPerRow) ): self.firstDayInMonth = self.firstDayInMonth - datetime.timedelta(days=7) self.numDays = (self.lastDayInMonth - self.firstDayInMonth + datetime.timedelta(days=1)).days self.numRows = int(self.numDays / ( 7 * self.weeksPerRow )) if ( self.numRows < ( 6 / self.weeksPerRow) ): self.lastDayInMonth = self.lastDayInMonth + datetime.timedelta(days=7) self.numDays = (self.lastDayInMonth - self.firstDayInMonth + datetime.timedelta(days=1)).days self.numRows = int(self.numDays / ( 7 * self.weeksPerRow )) def get(self): out = [] tmp = [] num_rows = 0 for i in range(0, self.numDays): tmp.append(self.firstDayInMonth + datetime.timedelta(days=i)) if i % ( 7 * self.weeksPerRow ) == ( 7 * self.weeksPerRow ) - 1: out.append(tmp) tmp = [] return out if __name__ == "__main__": x = MonthCalendarMatrix(2020,1,1,True) for i in x.get(): print(len(i))