Home > Software engineering >  Create lists for number of weeks in a month
Create lists for number of weeks in a month

Time:12-30

I'm trying to create a number of lists depending on the number of weeks there are in a month so for example, we have months that have exactly four weeks as we have months that may surpass that, so my requirement is to create lists dynamically depending the month the users select so the number of list is equal to the weeks in the selected month.

Any pointer would be helpful, thank you


    def _get_columns_name(self, options):
        
        
        # the data type = list
        header1 = [
            {'name': '', 'style': 'width:90%'},
            {'name': _('Week 1'), 'class': 'number', 'colspan': 2},
            {'name': options['date']['string'], 'class': 'number', 'colspan': 1},
        ]   [
            {'name': '', 'style': 'width:90%'},
            {'name': _('Week 2'), 'class': 'number', 'colspan': 2},
            {'name': options['date']['string'], 'class': 'number', 'colspan': 1},
        ]   [
            {'name': '', 'style': 'width:90%'},
            {'name': _('Week 3'), 'class': 'number', 'colspan': 2},
            {'name': options['date']['string'], 'class': 'number', 'colspan': 1},
        ]   [
            {'name': '', 'style': 'width:90%'},
            {'name': _('Week 4'), 'class': 'number', 'colspan': 2},
            {'name': options['date']['string'], 'class': 'number', 'colspan': 1},
        ]

        return [header1]

Currently I'm doing this but itdoes not satisfy the requirement correctly.

CodePudding user response:

Maybe the builtin Calendar library will be useful to you: for instance, to get the number of weeks in a certain month, you can use calendar.monthcalendar

import calendar

month_matrix = calendar.monthcalendar(year=2021, month=12)
num_weeks = len(month_matrix)

Then the loop is simple:

header1 = []
for i in range(num_weeks):
   header1.extend([
             {'name': '', 'style': 'width:90%'},
             {'name': _(f'Week {i 1}'), 'class': 'number', 'colspan': 2},
             {'name': options['date']['string'], 'class': 'number', 'colspan': 1},
])

CodePudding user response:

Simple way to do this using loops

    def _get_columns_name(options, weeks):
    
    
    # the data type = list
        header1 = [[
          {'name': '', 'style': 'width:90%'},
          {'name': _('Week {}'.format(i)), 'class': 'number', 'colspan': 2},
          {'name': options['date']['string'], 'class': 'number', 'colspan': 1}] for i in range(1, week 1)]

       return [header1]
  • Related