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

后端 未结 14 1670
梦如初夏
梦如初夏 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:29

    This method works for any mapping:

    month2quarter = {
            1:1,2:1,3:1,
            4:2,5:2,6:2,
            7:3,8:3,9:3,
            10:4,11:4,12:4,
        }.get
    

    We have just generated a function int->int

    month2quarter(9) # returns 3
    

    This method is also fool-proof

    month2quarter(-1) # returns None
    month2quarter('July') # returns None
    

提交回复
热议问题