Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Pandas - Format the Period object and display Quarter
To format the Period object in Pandas, use the period.strftime() method. To display the quarter, set the parameter as Q%q which shows the quarter number (Q1, Q2, Q3, or Q4).
Creating a Period Object
First, import pandas and create a Period object with specific date and time components ?
import pandas as pd
# Create a Period object with second frequency
period = pd.Period(freq="S", year=2021, month=9, day=18, hour=8, minute=20, second=45)
# Display the Period object
print("Period...")
print(period)
Period... 2021-09-18 08:20:45
Formatting to Display Quarter
Use strftime() with 'Q%q' format to display the quarter ?
import pandas as pd
period = pd.Period(freq="S", year=2021, month=9, day=18, hour=8, minute=20, second=45)
# Format Period object to display quarter
quarter_display = period.strftime('Q%q')
print("Quarter representation:")
print(quarter_display)
Quarter representation: Q3
Different Quarter Examples
Here are examples showing different months and their corresponding quarters ?
import pandas as pd
# Different months to show various quarters
periods = [
pd.Period(freq="D", year=2021, month=2, day=15), # Q1
pd.Period(freq="D", year=2021, month=5, day=10), # Q2
pd.Period(freq="D", year=2021, month=9, day=18), # Q3
pd.Period(freq="D", year=2021, month=11, day=25) # Q4
]
for period in periods:
print(f"Period: {period} ? Quarter: {period.strftime('Q%q')}")
Period: 2021-02-15 ? Quarter: Q1 Period: 2021-05-10 ? Quarter: Q2 Period: 2021-09-18 ? Quarter: Q3 Period: 2021-11-25 ? Quarter: Q4
Other Useful Format Codes
Besides Q%q, you can use other format codes with strftime() ?
import pandas as pd
period = pd.Period(freq="D", year=2021, month=9, day=18)
print("Different format codes:")
print(f"Year: {period.strftime('%Y')}")
print(f"Month: {period.strftime('%m')}")
print(f"Month name: {period.strftime('%B')}")
print(f"Quarter: {period.strftime('Q%q')}")
Different format codes: Year: 2021 Month: 09 Month name: September Quarter: Q3
Conclusion
Use period.strftime('Q%q') to format Period objects and display quarters as Q1, Q2, Q3, or Q4. The strftime() method supports various format codes for flexible date and time formatting in Pandas Period objects.
Advertisements
