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

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

    This is very simple and works in python3:

    from datetime import datetime
    
    # Get current date-time.
    now = datetime.now()
    
    # Determine which quarter of the year is now. Returns q1, q2, q3 or q4.
    quarter_of_the_year = 'q'+str((now.month-1)//3+1)
    
    0 讨论(0)
  • 2020-11-29 00:52

    using dictionaries, you can pull this off by

    def get_quarter(month):
        quarter_dictionary = {
            "Q1" : [1,2,3],
            "Q2" : [4,5,6],
            "Q3" : [7,8,9],
            "Q4" : [10,11,12]
        }
    
        for key,values in quarter_dictionary.items():
            for value in values:
                if value == month:
                    return key
    
    print(get_quarter(3))
    
    0 讨论(0)
提交回复
热议问题