Search code examples
pythonpandasdate

How to convert dates to quarters in Python?


I would like to convert my date column into an indicator of the quarter of that particular year, say 2018q1 or 2018q2 etc.

My data looks like this, I have stock returns once per quarter (not showing the return column here), and a corresponding date, the column quarter is what I would like to get (or something similar)

data = [
    {'date': '3/22/18', 'quarter': 1},
    {'date': '3/22/18', 'quarter': 1}, 
    {'date': '6/22/18', 'quarter': 3},
    {'date': '6/22/18', 'quarter': 3},
    {'date': '9/22/18', 'quarter': 2},
    {'date': '9/22/18', 'quarter': 2}]
df = pd.DataFrame(data, index=['s1', 's2','s1','s2','s1','s2'])

        date  quarter
 s1  3/22/13   2013q1
 s2  3/24/13   2013q1
 s1  6/21/13   2013q2
 s2  6/26/13   2013q2
 s1  9/21/13   2013q3
 s2  9/28/13   2013q3

Solution

  • Pandas has a method to help you, it's called pd.PeriodIndex(monthcolumn, freq= 'Q'). You may need to convert your month column to datatype first by using datetime libray.

    Pandas also have a method called 'to_date' that you can use to convert a column to a date column.

    For example:

    df["year"] = pd.to_date(df["year"])