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

后端 未结 14 1702
梦如初夏
梦如初夏 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条回答
  •  余生分开走
    2020-11-29 00:44

    Here is an example of a function that gets a datetime.datetime object and returns a unique string for each quarter:

    from datetime import datetime, timedelta
    
    def get_quarter(d):
        return "Q%d_%d" % (math.ceil(d.month/3), d.year)
    
    d = datetime.now()
    print(d.strftime("%Y-%m-%d"), get_q(d))
    
    d2 = d - timedelta(90)
    print(d2.strftime("%Y-%m-%d"), get_q(d2))
    
    d3 = d - timedelta(180 + 365)
    print(d3.strftime("%Y-%m-%d"), get_q(d3))
    

    And the output is:

    2019-02-14 Q1_2019
    2018-11-16 Q4_2018
    2017-08-18 Q3_2017
    

提交回复
热议问题