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)])
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;-).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With