I'm trying to create dates automatically from an initial date. 'Days' must remain the same for each month, the variables that should change are 'month' and 'year'. The variable 'composition' works as a counter in order to increase the months of the year until it reaches the upper level, and then the year should change and the count starts again.
I attached an example in order to explain.
This is the code:
import datetime
years = 6
composition = 4
date_str = '02/03/2017' # The date - 29 Dec 2017
format_str = '%d/%m/%Y' # The format
datetime_obj = datetime.datetime.strptime(date_str, format_str)
date = datetime_obj.date()
month = date.month
year = date.year
date_list = []
for j in range(1,int(years+1)):
for i in range(composition):
date = date.replace(month=month+3*i)
date_list.append(date)
i += 3
date = date.replace(year=year+j)
j += 1
print(date_list)
And this is the result:
[datetime.date(2017, 3, 2), datetime.date(2017, 6, 2), datetime.date(2017, 9, 2), datetime.date(2017, 12, 2), datetime.date(2018, 3, 2), datetime.date(2018, 6, 2), datetime.date(2018, 9, 2), datetime.date(2018, 12, 2), datetime.date(2019, 3, 2), datetime.date(2019, 6, 2), datetime.date(2019, 9, 2), datetime.date(2019, 12, 2), datetime.date(2020, 3, 2), datetime.date(2020, 6, 2), datetime.date(2020, 9, 2), datetime.date(2020, 12, 2), datetime.date(2021, 3, 2), datetime.date(2021, 6, 2), datetime.date(2021, 9, 2), datetime.date(2021, 12, 2), datetime.date(2022, 3, 2), datetime.date(2022, 6, 2), datetime.date(2022, 9, 2), datetime.date(2022, 12, 2)]
It works only for an initial variable date_str = '02/01/2017'
or date_str = '02/02/2017'
or date_str = '02/03/2017'
. But, when I change to date_str = '02/04/2017'
or above, the following error appears:
ValueError: month must be in 1..12
I want to be able to enter any month and the 'month' and 'year' fields of the date, change according to the correct format. I hope someone could help me with this error. Thanks!