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

后端 未结 14 1678
梦如初夏
梦如初夏 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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
    

提交回复
热议问题