Is there a Python function to determine which quarter of the year a date is in?

后端 未结 14 1677
梦如初夏
梦如初夏 2020-11-29 00:07

Sure I could write this myself, but before I go reinventing the wheel is there a function that already does this?

14条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 00:40

    This is an old question but still worthy of discussion.

    Here is my solution, using the excellent dateutil module.

      from dateutil import rrule,relativedelta
    
       year = this_date.year
       quarters = rrule.rrule(rrule.MONTHLY,
                          bymonth=(1,4,7,10),
                          bysetpos=-1,
                          dtstart=datetime.datetime(year,1,1),
                          count=8)
    
       first_day = quarters.before(this_date)
       last_day =  (quarters.after(this_date)
                    -relativedelta.relativedelta(days=1)
    

    So first_day is the first day of the quarter, and last_day is the last day of the quarter (calculated by finding the first day of the next quarter, minus one day).

提交回复
热议问题