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 - Indicate whether the date in DateTimeIndex is the last day of the month
To check whether dates in a DateTimeIndex correspond to the last day of their respective months, use the is_month_end property. This returns a boolean array indicating which dates fall on month-end dates.
Syntax
DateTimeIndex.is_month_end
Creating a DateTimeIndex
First, let's create a DateTimeIndex with various dates ?
import pandas as pd
# Create DateTimeIndex with 15-day intervals
datetimeindex = pd.date_range('2021-9-15 06:40:35', periods=6, tz='Australia/Adelaide', freq='15D')
print("DateTimeIndex...")
print(datetimeindex)
DateTimeIndex...
DatetimeIndex(['2021-09-15 06:40:35+09:30', '2021-09-30 06:40:35+09:30',
'2021-10-15 06:40:35+10:30', '2021-10-30 06:40:35+10:30',
'2021-11-14 06:40:35+10:30', '2021-11-29 06:40:35+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='15D')
Checking Month-End Dates
Use the is_month_end property to identify which dates are the last day of their month ?
import pandas as pd
datetimeindex = pd.date_range('2021-9-15 06:40:35', periods=6, tz='Australia/Adelaide', freq='15D')
# Check which dates are month-end dates
month_end_check = datetimeindex.is_month_end
print("Is month end?")
print(month_end_check)
# Display frequency for reference
print("\nDateTimeIndex frequency:")
print(datetimeindex.freq)
Is month end? [False True False False False False] DateTimeIndex frequency: <15 * Days>
Example with Different Dates
Let's create another example with specific month-end dates ?
import pandas as pd
# Create dates including some month-end dates
dates = ['2023-01-31', '2023-02-15', '2023-02-28', '2023-03-31', '2023-04-15']
datetimeindex = pd.to_datetime(dates)
print("Dates:")
for i, date in enumerate(datetimeindex):
print(f"{date.strftime('%Y-%m-%d')}: {datetimeindex.is_month_end[i]}")
Dates: 2023-01-31: True 2023-02-15: False 2023-02-28: True 2023-03-31: True 2023-04-15: False
Key Points
- Returns a boolean array with
Truefor month-end dates - Works with timezone-aware DateTimeIndex objects
- Considers the actual last day of each month (handles February, leap years, etc.)
- Useful for financial and time-series analysis
Conclusion
The is_month_end property provides an efficient way to identify month-end dates in a DateTimeIndex. It returns a boolean array that can be used for filtering or conditional operations in time-series data analysis.
Advertisements
