Python Pandas - Return numpy array of python datetime.date objects


To return numpy array of python datetime.date objects, use the datetimeindex.date property in Pandas.

At first, import the required libraries −

import pandas as pd

Create a DatetimeIndex with period 3 and frequency as us i.e. nanoseconds −

datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=3, tz='Australia/Sydney', freq='ns')

Display DateTimeIndex −

print("DateTimeIndex...\n", datetimeindex)

Returns only the date part of Timestamps without timezone information −

print("\nThe numpy array (date part)..\n",datetimeindex.date)

Example

Following is the code −

import pandas as pd

# DatetimeIndex with period 3 and frequency as us i.e. nanoseconds
# The timezone is Australia/Sydney
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=3, tz='Australia/Sydney', freq='ns')

# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)

# Returns only the date part of Timestamps without timezone information
print("\nThe numpy array (date part)..\n",datetimeindex.date)

Output

This will produce the following code −

DateTimeIndex...
DatetimeIndex([ '2021-10-20 02:30:50+11:00',
'2021-10-20 02:30:50.000000001+11:00',
'2021-10-20 02:30:50.000000002+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='N')

The numpy array (date part)..
[datetime.date(2021, 10, 20) datetime.date(2021, 10, 20)
datetime.date(2021, 10, 20)]

Updated on: 18-Oct-2021

514 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements