Jespar
Jespar

Reputation: 1026

Transform a datetime column to YYYYQx with quarter number

Is there an easy way to transform a datetime column in python to a format of YYYYQx, for example 2018Q1, 2018Q2 etc?

I've tried this line but returns nothing

zip([list(DF_A['period'].dt.year), ['Q']*length_of_DF, list(DF_A['period'].dt.quarter)])

Upvotes: 9

Views: 10252

Answers (2)

jpp
jpp

Reputation: 164693

Here is one way.

df = pd.DataFrame({'A': ['2017-01-01', '2017-04-01', '2017-12-01']})

df['A'] = pd.to_datetime(df['A'])
df['B'] = df['A'].dt.year.astype(str) + 'Q' + df['A'].dt.quarter.astype(str)

Result:

           A       B
0 2017-01-01  2017Q1
1 2017-04-01  2017Q2
2 2017-12-01  2017Q4

Upvotes: 3

jezrael
jezrael

Reputation: 862731

You can convert datetimes to quarter period by to_period and for custom strings use strftime:

d = ['2015-01-01','2016-05-01','2015-07-01','2015-10-01','2015-04-01']
df = pd.DataFrame({ 'Date': pd.to_datetime(d)})
print (df)
        Date
0 2015-01-01
1 2016-05-01
2 2015-07-01
3 2015-10-01
4 2015-04-01

print (df['Date'].dt.to_period('Q'))
0   2015Q1
1   2016Q2
2   2015Q3
3   2015Q4
4   2015Q2
Name: Date, dtype: object

print (df['Date'].dt.to_period('Q').dt.strftime('%Yq%q'))
0    2015q1
1    2016q2
2    2015q3
3    2015q4
4    2015q2
Name: Date, dtype: object

Upvotes: 12

Related Questions