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

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

    Here is a verbose, but also readable solution that will work for datetime and date instances

    def get_quarter(date):
        for months, quarter in [
            ([1, 2, 3], 1),
            ([4, 5, 6], 2),
            ([7, 8, 9], 3),
            ([10, 11, 12], 4)
        ]:
            if date.month in months:
                return quarter
    

提交回复
热议问题