在一年中的每个季度进行迭代

时间:2018-12-23 10:32:46

标签: python python-3.x datetime rrule

我试图在一年中的每个季度进行迭代,这是我到目前为止的工作。

now = datetime.now()

first_day = datetime(year=now.year, month=1, day=1)
print("--",first_day)
hundredDaysLater = first_day - timedelta(days=100)

for dt in rrule.rrule(rrule.MONTHLY, dtstart=first_day, bymonthday=(31, -1), count=6, interval=3):
    print(dt.replace(day=1))
    print(dt)

输出

  -- 2018-01-01 00:00:00
    2018-01-01 00:00:00
    2018-01-31 00:00:00
    2018-04-01 00:00:00
    2018-04-30 00:00:00
    2018-07-01 00:00:00
    2018-07-31 00:00:00
    2018-10-01 00:00:00
    2018-10-31 00:00:00
    2019-01-01 00:00:00
    2019-01-31 00:00:00
    2019-04-01 00:00:00

现在我基本上需要获取此输出

2018-01-01, 2018-03-31
2018-04-01, 2018-06-30
2018-07-01, 2018-09-30
2018-10-01, 2018-12-31

但是我不需要倒数,而是倒数。

2 个答案:

答案 0 :(得分:1)

使用relativedelta(来自dateutil包):

>>> from dateutil.relativedelta import relativedelta                                                                                                                  
>>> from datetime import date 
>>> d = date(2019, 1, 1)                                                                                                                                              
>>> day = relativedelta(days=1)                                                                                                                                       
>>> quarter = relativedelta(months=3)                                                                                                                                 
>>> while True: 
...     print(d - day) 
...     print(d - quarter) 
...     d -= quarter 
...                                                                                                                                                                   
2018-12-31
2018-10-01
2018-09-30
2018-07-01
2018-06-30
2018-04-01
2018-03-31
2018-01-01
2017-12-31
2017-10-01
2017-09-30
2017-07-01
2017-06-30
2017-04-01
2017-03-31
...

答案 1 :(得分:0)

具有 pandas.date_range 功能的简短解决方案:

cordova-sqlite-storage