Home > OS >  Get the last day of every month using static date in python?
Get the last day of every month using static date in python?

Time:07-14

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.

CodePudding user response:

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')

CodePudding user response:

from datetime import timedelta    

month_end_date = pd.to_datetime('30/06/2022')
dates = pd.date_range(start=month_end_date, freq='m', end=month_end_date timedelta(days=365))

Then create a dataframe:

df = pd.DataFrame(data=dates, columns=['date'])

If you want to add this column to existed dataframe:

df['date'] = dates
  • Related