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

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

How to insert 'Quarterly Dates' using for loop?

问题

  1. for y in range(2023,2027):
  2. for m in range(0, 12, 3):
  3. if (y==2026) and (m>0):
  4. continue
  5. 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.

  1. list_of_months = []
  2. for y in range(2023,2027):
  3. for m in range(12):
  4. if (y==2026) and (m>0):
  5. continue
  6. 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.

  1. list_of_qaurters = []
  2. for y in range(2023,2027):
  3. for m in range(12):
  4. if (y==2026) and (m>0):
  5. continue
  6. list_of_qaurters.append(datetime.datetime(year=y, month=m+1, day=1).strftime('%y-%m-%d'))
  1. ValueError: month must be in 1..12

答案1

得分: 0

为了最小化日期递增的迭代次数,我建议使用dateutil模块。

首先,您需要安装它。

  1. import datetime
  2. from dateutil.relativedelta import relativedelta
  3. list_of_qaurters = []
  4. start_year = year = 2023
  5. next_quarter_date = datetime.datetime(year=start_year, month=1, day=1)
  6. end_quarter_date = datetime.datetime(year=2027, month=12, day=31)
  7. list_of_qaurters.append(next_quarter_date.strftime('%y-%m-%d'))
  8. while next_quarter_date < end_quarter_date:
  9. next_quarter_date += relativedelta(months=+3)
  10. if next_quarter_date <= end_quarter_date:
  11. list_of_qaurters.append(next_quarter_date.strftime('%y-%m-%d'))
  12. print(list_of_qaurters)
英文:

To minimize iterations for date increment, I suggest to use dateutil module.

first you need to install it.

  1. pip install python-dateutil
  1. import datetime
  2. from dateutil.relativedelta import relativedelta
  3. list_of_qaurters = []
  4. start_year = year= 2023
  5. next_qaurter_date =datetime.datetime(year=start_year, month=1, day=1)
  6. end_qaurter_date = datetime.datetime(year=2027, month=12, day=31)
  7. list_of_qaurters.append(next_qaurter_date.strftime(&#39;%y-%m-%d&#39;))
  8. while next_qaurter_date &lt; end_qaurter_date:
  9. next_qaurter_date += relativedelta(months=+3)
  10. if (next_qaurter_date&lt;=end_qaurter_date):
  11. list_of_qaurters.append(next_qaurter_date.strftime(&#39;%y-%m-%d&#39;))
  12. 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:

确定