Issue
I have a static date eg month_end_date = 30/06/2022,
how can I get the last day of the month for each month from the month_end_date until next year 30/06/2023 in a dataframe column.
Just the last day of the month without creating an entire date range
Example output :
day
30
31
30
31
...
Solution
You can use pandas.date_range
with a month-end (M
) frequency:
month_end_date = '30/06/2022'
stop = '30/06/2023'
pd.date_range(month_end_date, stop, freq='M')
output:
DatetimeIndex(['2022-06-30', '2022-07-31', '2022-08-31', '2022-09-30',
'2022-10-31', '2022-11-30', '2022-12-31', '2023-01-31',
'2023-02-28', '2023-03-31', '2023-04-30', '2023-05-31',
'2023-06-30'],
dtype='datetime64[ns]', freq='M')
For only the days:
month_end_date = '30/06/2022'
stop = '30/06/2023'
pd.date_range(month_end_date, stop, freq='M').day
Output:
Int64Index([30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30], dtype='int64')
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.