Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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. This property returns an Int64Index containing the nanosecond values for each datetime in the index.
Syntax
DateTimeIndex.nanosecond
Creating DateTimeIndex with Nanosecond Frequency
First, let's create a DateTimeIndex with nanosecond frequency to demonstrate the nanosecond extraction ?
import pandas as pd
# Create DatetimeIndex with period 6 and frequency as ns (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)
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')
Extracting Nanoseconds
Now we can extract the nanosecond component using the nanosecond property ?
import pandas as pd
# Create DatetimeIndex with nanosecond frequency
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Sydney', freq='ns')
# Display DateTimeIndex frequency
print("DateTimeIndex frequency...\n", datetimeindex.freq)
# Extract the nanoseconds
print("\nGetting the nanoseconds...\n", datetimeindex.nanosecond)
DateTimeIndex frequency... <Nano> Getting the nanoseconds... Int64Index([0, 1, 2, 3, 4, 5], dtype='int64')
How It Works
The nanosecond property extracts the nanosecond component (0-999) from each datetime in the DateTimeIndex. In our example:
- First timestamp: 0 nanoseconds (base time)
- Second timestamp: 1 nanosecond added
- Third timestamp: 2 nanoseconds added
- And so on...
Conclusion
The DateTimeIndex.nanosecond property provides an efficient way to extract nanosecond components from datetime objects. This is particularly useful when working with high-frequency time series data that requires nanosecond precision.
