Python Pandas - Return DatetimeIndex as object ndarray of datetime.datetime objects

PythonServer Side ProgrammingProgramming

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)]
raja
Updated on 19-Oct-2021 10:06:45

Advertisements