Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)])
like image 953
Jespar Avatar asked Mar 19 '18 12:03

Jespar


People also ask

How do you extract a quarter in Python?

date, (x. month-1)//3 will give you the quarter (0 for first quarter, 1 for second quarter, etc -- add 1 if you need to count from 1 instead;-).


1 Answers

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
like image 125
jezrael Avatar answered Nov 14 '22 22:11

jezrael