You can use the following methods to get the quarter from a date in a pandas DataFrame:
Method 1: Get Quarter from Date (Year & Quarter Format)
df['quarter'] = pd.PeriodIndex(df.date, freq='Q')
If the date is in the first quarter of 2022, this will return the quarter in a format like 2022Q1.
Method 2: Get Quarter from Date (Quarter Number Format)
df['quarter'] = df['date'].dt.quarter
If the date is in the first quarter of 2022, this will simply return the value 1.
The following examples shows how to use this syntax in practice with the following pandas DataFrame:
import pandas as pd
#create DataFrame
df = pd.DataFrame({'date': pd.date_range(start='1/1/2022', freq='M', periods=14),
'sales': [6, 8, 10, 5, 4, 8, 8, 3, 5, 14, 8, 3, 10, 12]})
#view DataFrame
print(df)
date sales
0 2022-01-31 6
1 2022-02-28 8
2 2022-03-31 10
3 2022-04-30 5
4 2022-05-31 4
5 2022-06-30 8
6 2022-07-31 8
7 2022-08-31 3
8 2022-09-30 5
9 2022-10-31 14
10 2022-11-30 8
11 2022-12-31 3
12 2023-01-31 10
13 2023-02-28 12
Example 1: Get Quarter from Date (Year & Quarter Format)
We can use the following code to create a new column called quarter that extracts the quarter from the date column in a year and quarter format:
#create new column that displays year and quarter from date column
df['quarter'] = pd.PeriodIndex(df.date, freq='Q')
#view updated DataFrame
print(df)
date sales quarter
0 2022-01-31 6 2022Q1
1 2022-02-28 8 2022Q1
2 2022-03-31 10 2022Q1
3 2022-04-30 5 2022Q2
4 2022-05-31 4 2022Q2
5 2022-06-30 8 2022Q2
6 2022-07-31 8 2022Q3
7 2022-08-31 3 2022Q3
8 2022-09-30 5 2022Q3
9 2022-10-31 14 2022Q4
10 2022-11-30 8 2022Q4
11 2022-12-31 3 2022Q4
12 2023-01-31 10 2023Q1
13 2023-02-28 12 2023Q1
The new column called quarter contains the quarter from the date column in a year and quarter format.
Example 2: Get Quarter from Date (Quarter Number Format)
We can use the following code to create a new column called quarter that extracts the quarter from the date column in a quarter number format
#create new column that displays quarter from date column
df['quarter'] = df['date'].dt.quarter
#view updated DataFrame
print(df)
date sales quarter
0 2022-01-31 6 1
1 2022-02-28 8 1
2 2022-03-31 10 1
3 2022-04-30 5 2
4 2022-05-31 4 2
5 2022-06-30 8 2
6 2022-07-31 8 3
7 2022-08-31 3 3
8 2022-09-30 5 3
9 2022-10-31 14 4
10 2022-11-30 8 4
11 2022-12-31 3 4
12 2023-01-31 10 1
13 2023-02-28 12 1
The new column called quarter contains the quarter number from the date column in a quarter number format.
Additional Resources
The following tutorials explain how to perform other common operations in pandas:
How to Add and Subtract Days from a Date in Pandas
How to Select Rows Between Two Dates in Pandas
How to Create Date Column from Year, Month and Day in Pandas