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

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

    IF you are already using pandas, it's quite simple.

    import datetime as dt
    import pandas as pd
    
    quarter = pd.Timestamp(dt.date(2016, 2, 29)).quarter
    assert quarter == 1
    

    If you have a date column in a dataframe, you can easily create a new quarter column:

    df['quarter'] = df['date'].dt.quarter
    
    0 讨论(0)
  • 2020-11-29 00:26

    For those, who are looking for financial year quarter data, using pandas,

    import datetime
    import pandas as pd
    today_date = datetime.date.today()
    quarter = pd.PeriodIndex(today_date, freq='Q-MAR').strftime('Q%q')
    

    reference: pandas period index

    0 讨论(0)
  • 2020-11-29 00:27

    hmmm so calculations can go wrong, here is a better version (just for the sake of it)

    first, second, third, fourth=1,2,3,4# you can make strings if you wish :)
    
    quarterMap = {}
    quarterMap.update(dict(zip((1,2,3),(first,)*3)))
    quarterMap.update(dict(zip((4,5,6),(second,)*3)))
    quarterMap.update(dict(zip((7,8,9),(third,)*3)))
    quarterMap.update(dict(zip((10,11,12),(fourth,)*3)))
    
    print quarterMap[6]
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-29 00:30
    for m in range(1, 13):
      print ((m*3)//10)
    
    0 讨论(0)
  • 2020-11-29 00:34

    I would suggest another arguably cleaner solution. If X is a datetime.datetime.now() instance, then the quarter is:

    import math
    Q=math.ceil(X.month/3.)
    

    ceil has to be imported from math module as it can't be accessed directly.

    0 讨论(0)
提交回复
热议问题