英文:
How to insert 'Quarterly Dates' using for loop?
问题
for y in range(2023,2027):
for m in range(0, 12, 3):
if (y==2026) and (m>0):
continue
list_of_qaurters.append(datetime.datetime(year=y, month=m+1, day=1).strftime('%Y-%m-%d'))
英文:
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
答案1
得分: 0
为了最小化日期递增的迭代次数,我建议使用dateutil模块。
首先,您需要安装它。
import datetime
from dateutil.relativedelta import relativedelta
list_of_qaurters = []
start_year = year = 2023
next_quarter_date = datetime.datetime(year=start_year, month=1, day=1)
end_quarter_date = datetime.datetime(year=2027, month=12, day=31)
list_of_qaurters.append(next_quarter_date.strftime('%y-%m-%d'))
while next_quarter_date < end_quarter_date:
next_quarter_date += relativedelta(months=+3)
if next_quarter_date <= end_quarter_date:
list_of_qaurters.append(next_quarter_date.strftime('%y-%m-%d'))
print(list_of_qaurters)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论