How to insert 'Quarterly Dates' using for loop?
Question:
I tried to generate quarterly dates using for loop using an existing line of code for generating monthly dates.
list_of_months = []
for y in range(2023,2027):
for m in range(12):
if (y==2026) and (m>0):
continue
list_of_months.append(datetime.datetime(year=y, month=m+1, day=1).strftime('%Y-%m-%d'))
I tried to change the value of month from "month=m+1" to "month=m+3" and I’m getting the following error.
list_of_qaurters = []
for y in range(2023,2027):
for m in range(12):
if (y==2026) and (m>0):
continue
list_of_qaurters.append(datetime.datetime(year=y, month=m+1, day=1).strftime('%y-%m-%d'))
ValueError: month must be in 1..12
Answers:
To minimize iterations for date increment, I suggest to use dateutil module.
first you need to install it.
pip install python-dateutil
import datetime
from dateutil.relativedelta import relativedelta
list_of_qaurters = []
start_year = year= 2023
next_qaurter_date =datetime.datetime(year=start_year, month=1, day=1)
end_qaurter_date = datetime.datetime(year=2027, month=12, day=31)
list_of_qaurters.append(next_qaurter_date.strftime('%y-%m-%d'))
while next_qaurter_date < end_qaurter_date:
next_qaurter_date += relativedelta(months=+3)
if (next_qaurter_date<=end_qaurter_date):
list_of_qaurters.append(next_qaurter_date.strftime('%y-%m-%d'))
print(list_of_qaurters)
I tried to generate quarterly dates using for loop using an existing line of code for generating monthly dates.
list_of_months = []
for y in range(2023,2027):
for m in range(12):
if (y==2026) and (m>0):
continue
list_of_months.append(datetime.datetime(year=y, month=m+1, day=1).strftime('%Y-%m-%d'))
I tried to change the value of month from "month=m+1" to "month=m+3" and I’m getting the following error.
list_of_qaurters = []
for y in range(2023,2027):
for m in range(12):
if (y==2026) and (m>0):
continue
list_of_qaurters.append(datetime.datetime(year=y, month=m+1, day=1).strftime('%y-%m-%d'))
ValueError: month must be in 1..12
To minimize iterations for date increment, I suggest to use dateutil module.
first you need to install it.
pip install python-dateutil
import datetime
from dateutil.relativedelta import relativedelta
list_of_qaurters = []
start_year = year= 2023
next_qaurter_date =datetime.datetime(year=start_year, month=1, day=1)
end_qaurter_date = datetime.datetime(year=2027, month=12, day=31)
list_of_qaurters.append(next_qaurter_date.strftime('%y-%m-%d'))
while next_qaurter_date < end_qaurter_date:
next_qaurter_date += relativedelta(months=+3)
if (next_qaurter_date<=end_qaurter_date):
list_of_qaurters.append(next_qaurter_date.strftime('%y-%m-%d'))
print(list_of_qaurters)