Md. Tanvir Raihan
Md. Tanvir Raihan

Reputation: 4285

python generate period of a year in a list of dictionary

I am relatively new in python. I am trying generate a period of a year in list of dictionary; something like this,

[{'end_date': '2016-01-31', 'start_date': '2016-01-01'},
 {'end_date': '2016-01-31', 'start_date': '2016-01-01'},
 {'end_date': '2016-01-31', 'start_date': '2016-01-01'},
 {'end_date': '2016-01-31', 'start_date': '2016-01-01'},
 {'end_date': '2016-01-31', 'start_date': '2016-01-01'},
 {'end_date': '2016-01-31', 'start_date': '2016-01-01'},
 {'end_date': '2016-01-31', 'start_date': '2016-01-01'},
 {'end_date': '2016-01-31', 'start_date': '2016-01-01'},
 {'end_date': '2016-01-31', 'start_date': '2016-01-01'},
 {'end_date': '2016-01-31', 'start_date': '2016-01-01'},
 {'end_date': '2016-01-31', 'start_date': '2016-01-01'},
 {'end_date': '2016-01-31', 'start_date': '2016-01-01'}]

fot this output I have created the following function:

def get_periods():
    year = raw_input('Enter an year')
    list_of_periods = []
    for k in range(12):
        list_of_periods.append({'start_date': year + '-01-01','end_date': year + '-01-31'})
    return list_of_periods

Here I just want to pass the year and it should generate a period of a year, that is

[{'end_date': '2016-01-31', 'start_date': '2016-01-01'},
 {'end_date': '2016-02-29', 'start_date': '2016-02-01'},
 ....... and so on]

but I don't know how to iterate over day and month to create appropriate periods of a year. Also there are the issues of leap year and month of 30 days or month of 31 days.

Upvotes: 1

Views: 1131

Answers (1)

Selcuk
Selcuk

Reputation: 59315

You can use the calendar.monthrange() to find the last day of any month:

import calendar

def get_periods():
    year = int(input('Enter a year: '))
    list_of_periods = []
    for month in range(1, 13):
        last_day = calendar.monthrange(year, month)[1]
        list_of_periods.append({'start_date': '{0}-{1:02}-01'.format(year, month),
                                'end_date': '{0}-{1:02}-{2}'.format(year, month, last_day)})

    return list_of_periods

print(get_periods())

You will get a similar output to the following when you run this:

Enter a year: 2016
[{'start_date': '2016-01-01', 'end_date': '2016-01-31'}, 
 {'start_date': '2016-02-01', 'end_date': '2016-02-29'}, 
 {'start_date': '2016-03-01', 'end_date': '2016-03-31'}, 
 {'start_date': '2016-04-01', 'end_date': '2016-04-30'}, 
 ...]

Upvotes: 4

Related Questions