如何使用for循环插入“季度日期”?

huangapple go评论79阅读模式
英文:

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(&#39;%y-%m-%d&#39;))

while next_qaurter_date &lt; end_qaurter_date:
    next_qaurter_date +=  relativedelta(months=+3)
    if (next_qaurter_date&lt;=end_qaurter_date):
        list_of_qaurters.append(next_qaurter_date.strftime(&#39;%y-%m-%d&#39;))
    

print(list_of_qaurters)

huangapple
  • 本文由 发表于 2023年3月9日 18:17:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75683211.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定