> ## Content Index
> Fetch the complete content index at: https://datascientyst.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# How to  Convert DateTime to Quarter in Pandas
- URL: https://datascientyst.com/convert-datetime-to-quarter-in-pandas/
- Published: 2021-08-14T09:28:26.000Z
- Updated: 2022-10-28T06:08:39.000Z
- Author: John D K
- Tags: Time Series

Need to rename convert string or datetime to quarter in Pandas?

If so, you may use the following syntax to extract quarter info from your DataFrame:

```python
df['Date'].dt.to_period('Q')

```

The picture below demonstrate it:

![convert-datetime-to-quarter-in-pandas](https://datascientyst.com/content/images/2022/10/convert-datetime-to-quarter-in-pandas.webp)

To begin, let's create a simple DataFrame with a datetime column:

```python
import pandas as pd
dates = ['2021-01-01', '2021-05-02', '2021-08-03']
df = pd.DataFrame({'StartDate': dates})

df['StartDate'] = pd.to_datetime(df['StartDate'])

df

```

| StartDate  |
| ---------- |
| 2021-01-01 |
| 2021-05-02 |
| 2021-08-03 |

## Step 1: Extract Quarter as YYYYMM from DataTime Column in Pandas

Let's say that you want to extract the quarter info in the next format: `YYYYMM`. Pandas offers a built-in method for this purpose `.dt.to_period('Q')`:

```python
df['quarter'] = df['StartDate'].dt.to_period('Q')

```

the result would be:

```
0    2021Q1
1    2021Q2
2    2021Q3

```

## Step 2: Extract Quarter(custom format) from DataTime Column in Pandas

What if you like to get a custom format instead of the default one? In this case you can use method: `dt.strftime('q%q %y\'')` to change the format like:

```python
df['quarter_custom'] = df['StartDate'].dt.to_period('Q').dt.strftime('q%q %y\'')

```

This will output:

```
0    q1 21'
1    q2 21'
2    q3 21'

```

Another option for custom formatting might be separated extraction of the information as:

```python
df['StartDate'].dt.year.astype(str) + '-' + df['StartDate'].dt.quarter.astype(str)

```

## Step 3: Extract Quarters without the year

If you need to analyse the quarter info without the year information you can get it by:

```python
df['StartDate'].dt.quarter

```

## Resources

- [Notebook - Convert DateTime to Quarter in Pandas](https://github.com/softhints/datascientyst/blob/master/datetime/2.convert-datetime-to-quarter-in-pandas.ipynb?ref=datascientyst.com)