![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 - Return DatetimeIndex as object ndarray of datetime.datetime objects
To return DatetimeIndex as object ndarray of datetime.datetime objects, use the datetimeindex.to_pydatetime() method.
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)
Return DatetimeIndex as object ndarray −
print("\nReturn DatetimeIndex as object ndarray of datetime.datetime objects...\n", datetimeindex.to_pydatetime())
Example
Following is the code −
import pandas as pd # 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) # display DateTimeIndex frequency print("DateTimeIndex frequency...\n", datetimeindex.freq) # Return DatetimeIndex as object ndarray print("\nReturn DatetimeIndex as object ndarray of datetime.datetime objects...\n", datetimeindex.to_pydatetime())
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> Return DatetimeIndex as object ndarray of datetime.datetime objects... [datetime.datetime(2021, 12, 31, 7, 20, 32, 261811) datetime.datetime(2023, 12, 31, 7, 20, 32, 261811) datetime.datetime(2025, 12, 31, 7, 20, 32, 261811) datetime.datetime(2027, 12, 31, 7, 20, 32, 261811) datetime.datetime(2029, 12, 31, 7, 20, 32, 261811)]
Advertisements