Python Pandas - Extract the nanoseconds from the DateTimeIndex with specific time series frequency


To extract the nanoseconds from the DateTimeIndex with specific time series frequency, use the DateTimeIndex.nanosecond property.

At first, import the required libraries −

import pandas as pd

Create a DatetimeIndex with period 6 and frequency as ns i.e. nanoseconds −

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

Display DateTimeIndex −

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

Get the nanoseconds −

print("\nGetting the nanoseconds..\n",datetimeindex.nanosecond)

Example

Following is the code −

import pandas as pd

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

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

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

# get the nanoseconds
print("\nGetting the nanoseconds..\n",datetimeindex.nanosecond)

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',
'2021-10-20 02:30:50.000000003+11:00',
'2021-10-20 02:30:50.000000004+11:00',
'2021-10-20 02:30:50.000000005+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='N')
DateTimeIndex frequency...
<Nano>

Getting the nanoseconds..
Int64Index([0, 1, 2, 3, 4, 5], dtype='int64')

Updated on: 18-Oct-2021

451 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements