 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Pandas - How to convert DateTimeIndex to Period
To convert DateTimeIndex to Period, use the datetimeindex.to_period() method in Pandas. The frequency is set using the freq parameter.
At first, import the required libraries −
import pandas as pd
Create a DatetimeIndex with period 5 and frequency as Y i.e. year −
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, freq='2Y')  Display DateTimeIndex −
print("DateTimeIndex...\n", datetimeindex) Convert DateTimeIndex to Period. We have set the frequency as Month using the "freq" parameter with value 'M' −
print("\nConvert DateTimeIndex to Period...\n", datetimeindex.to_period(freq='M')) Example
Following is the code −
import pandas as pd # DatetimeIndex with period 5 and frequency as Y i.e. year # timezone is Australia/Adelaide datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, freq='2Y') # display DateTimeIndex print("DateTimeIndex...\n", datetimeindex) # display DateTimeIndex frequency print("DateTimeIndex frequency...\n", datetimeindex.freq) # Convert DateTimeIndex to Period # We have set the frequency as Month using the "freq" parameter with value 'M' print("\nConvert DateTimeIndex to Period...\n", datetimeindex.to_period(freq='M'))  Output
This will produce the following code −
DateTimeIndex... DatetimeIndex(['2021-12-31 07:20:32.261811624', '2023-12-31 07:20:32.261811624', '2025-12-31 07:20:32.261811624', '2027-12-31 07:20:32.261811624', '2029-12-31 07:20:32.261811624'], dtype='datetime64[ns]', freq='2A-DEC') DateTimeIndex frequency... <2 * YearEnds: month=12> Convert DateTimeIndex to Period... PeriodIndex(['2021-12', '2023-12', '2025-12', '2027-12', '2029-12'], dtype='period[M]')
Advertisements
 