Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 731
Niccola Tartaglia Avatar asked May 22 '18 03:05

Niccola Tartaglia


People also ask

How does Python calculate quarters?

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;-).

How do I convert a date in python?

For this, we will use the strptime() method and Pandas module. This method is used to create a DateTime object from a string. Then we will extract the date from the DateTime object using the date() function and dt. date from Pandas in Python.

How do you change Panda month to quarter?

to_datetime(x['Mth']. values). astype('period[Q]') works, but pd. to_datetime(x['Mth']).

How do you convert a period to a string in Python?

To format and return the string representation of the Period object, use the period. strftime() method. With that, set the format specifiers as an argument like strftime('%d-%b-%Y').


1 Answers

to_datetime:

df.date = pd.to_datetime(df.date)

PeriodIndex

df['quarter'] = pd.PeriodIndex(df.date, freq='Q')

         date quarter
s1 2018-03-22  2018Q1
s2 2018-03-22  2018Q1
s1 2018-06-22  2018Q2
s2 2018-06-22  2018Q2
s1 2018-09-22  2018Q3
s2 2018-09-22  2018Q3
like image 155
user3483203 Avatar answered Sep 25 '22 11:09

user3483203