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 microseconds from the DateTimeIndex with specific time series frequency
To extract the microseconds from a DateTimeIndex with specific time series frequency, use the DateTimeIndex.microsecond property. This property returns an Index containing the microsecond component of each datetime.
Creating DateTimeIndex with Microsecond Frequency
First, let's create a DateTimeIndex with microsecond frequency ?
import pandas as pd
# Create DatetimeIndex with period 6 and frequency as 'us' (microseconds)
# The timezone is Australia/Sydney
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Sydney', freq='us')
print("DateTimeIndex...")
print(datetimeindex)
DateTimeIndex...
DatetimeIndex(['2021-10-20 02:30:50+11:00',
'2021-10-20 02:30:50.000001+11:00',
'2021-10-20 02:30:50.000002+11:00',
'2021-10-20 02:30:50.000003+11:00',
'2021-10-20 02:30:50.000004+11:00',
'2021-10-20 02:30:50.000005+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='U')
Extracting Microseconds
Now let's extract the microsecond component from each datetime ?
import pandas as pd
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Sydney', freq='us')
# Display frequency information
print("DateTimeIndex frequency:")
print(datetimeindex.freq)
# Extract microseconds using the microsecond property
microseconds = datetimeindex.microsecond
print("\nMicroseconds extracted:")
print(microseconds)
print(f"\nType: {type(microseconds)}")
DateTimeIndex frequency: <Micro> Microseconds extracted: Index([0, 1, 2, 3, 4, 5], dtype='int64') Type: <class 'pandas.core.indexes.base.Index'>
Understanding the Results
The microsecond property returns values from 0 to 999999, representing the microsecond component of each datetime. In our example, the DateTimeIndex starts at exactly 02:30:50 (0 microseconds) and increments by 1 microsecond for each subsequent datetime.
import pandas as pd
# Example with larger microsecond values
datetimeindex = pd.date_range('2021-10-20 02:30:50.123456', periods=4, freq='100us')
print("DateTimeIndex with larger microsecond values:")
print(datetimeindex)
print("\nExtracted microseconds:")
print(datetimeindex.microsecond)
DateTimeIndex with larger microsecond values:
DatetimeIndex(['2021-10-20 02:30:50.123456',
'2021-10-20 02:30:50.123556',
'2021-10-20 02:30:50.123656',
'2021-10-20 02:30:50.123756'],
dtype='datetime64[ns]', freq='100U')
Extracted microseconds:
Index([123456, 123556, 123656, 123756], dtype='int64')
Conclusion
The DateTimeIndex.microsecond property efficiently extracts microsecond components from datetime objects. It returns an Index with integer values ranging from 0 to 999999, making it useful for time-based analysis and filtering operations.
