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
Selected Reading
Python Pandas - Extract the day from the DateTimeIndex with specific time series frequency
To extract the day from the DateTimeIndex with specific time series frequency, use the DateTimeIndex.day property. This property returns the day component from each datetime in the index as integers.
Syntax
DateTimeIndex.day
This property returns an Int64Index containing the day values (1-31) for each datetime in the DateTimeIndex.
Creating a DateTimeIndex
First, let's create a DateTimeIndex with daily frequency ?
import pandas as pd
# Create DatetimeIndex with period 6 and frequency as D (daily)
# Using Australia/Sydney timezone
datetimeindex = pd.date_range('2021-10-20 02:35:55', periods=6, tz='Australia/Sydney', freq='D')
print("DateTimeIndex...")
print(datetimeindex)
DateTimeIndex...
DatetimeIndex(['2021-10-20 02:35:55+11:00', '2021-10-21 02:35:55+11:00',
'2021-10-22 02:35:55+11:00', '2021-10-23 02:35:55+11:00',
'2021-10-24 02:35:55+11:00', '2021-10-25 02:35:55+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='D')
Extracting Day Values
Now extract the day component using the .day property ?
import pandas as pd
# Create DatetimeIndex with daily frequency
datetimeindex = pd.date_range('2021-10-20 02:35:55', periods=6, tz='Australia/Sydney', freq='D')
# Display DateTimeIndex
print("DateTimeIndex...")
print(datetimeindex)
# Display DateTimeIndex frequency
print("\nDateTimeIndex frequency...")
print(datetimeindex.freq)
# Extract the day component
print("\nExtracting the day...")
print(datetimeindex.day)
DateTimeIndex...
DatetimeIndex(['2021-10-20 02:35:55+11:00', '2021-10-21 02:35:55+11:00',
'2021-10-22 02:35:55+11:00', '2021-10-23 02:35:55+11:00',
'2021-10-24 02:35:55+11:00', '2021-10-25 02:35:55+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='D')
DateTimeIndex frequency...
<Day>
Extracting the day...
Int64Index([20, 21, 22, 23, 24, 25], dtype='int64')
Key Points
- The
.dayproperty extracts day values from 1 to 31 - Returns an Int64Index with the same length as the original DateTimeIndex
- Works with any timezone-aware or timezone-naive DateTimeIndex
- The frequency of the original DateTimeIndex doesn't affect the extraction
Conclusion
The DateTimeIndex.day property provides a simple way to extract day components from datetime indices. This is useful for time series analysis where you need to group or filter data by day of the month.
Advertisements
