Skip to content
Advertisement

Display/return last 12 and 24 months with year from current month and year using python (Creating Date range)

today = pd.to_datetime('today').strftime("%d/%m/%Y")
last = (pd.to_datetime(today) - pd.DateOffset(years=1)).strftime("%d/%m/%Y")

listofmonths = pd.date_range(start=last, end=today, freq='MS') 
listofmonths


Result / Output:

DatetimeIndex(['2021-06-01', '2021-07-01', '2021-08-01', '2021-09-01',
               '2021-10-01', '2021-11-01', '2021-12-01', '2022-01-01',
               '2022-02-01', '2022-03-01', '2022-04-01', '2022-05-01'],
                dtype='datetime64[ns]', freq='MS')

Question:

Here i got first date of the month but along with first date i want last date of the month as well. So how it will be possible. What change should i make to get the last date of the month as well?

Advertisement

Answer

To ge the end of the months you can do:

from pandas.tseries.offsets import MonthEnd

month_ends = listofmonths + MonthEnd(1)

print(month_ends)
DatetimeIndex(['2021-06-30', '2021-07-31', '2021-08-31', '2021-09-30',
               '2021-10-31', '2021-11-30', '2021-12-31', '2022-01-31',
               '2022-02-28', '2022-03-31', '2022-04-30', '2022-05-31'],
              dtype='datetime64[ns]', freq=None)

If you want a single index:

joined_index = listofmonths.union(month_ends)

print(joined_index)
DatetimeIndex(['2021-06-01', '2021-06-30', '2021-07-01', '2021-07-31',
               '2021-08-01', '2021-08-31', '2021-09-01', '2021-09-30',
               '2021-10-01', '2021-10-31', '2021-11-01', '2021-11-30',
               '2021-12-01', '2021-12-31', '2022-01-01', '2022-01-31',
               '2022-02-01', '2022-02-28', '2022-03-01', '2022-03-31',
               '2022-04-01', '2022-04-30', '2022-05-01', '2022-05-31'],
              dtype='datetime64[ns]', freq=None)

EDIT – after discussion in the comments:

To get the string tuples you can do:

month_tuples = list(zip(listofmonths.astype(str), month_ends.astype(str)))
print(month_tuples)
[('2021-06-01', '2021-06-30'), ('2021-07-01', '2021-07-31'), 
('2021-08-01', '2021-08-31'), ('2021-09-01', '2021-09-30'), 
('2021-10-01', '2021-10-31'), ('2021-11-01', '2021-11-30'), 
('2021-12-01', '2021-12-31'), ('2022-01-01', '2022-01-31'), 
('2022-02-01', '2022-02-28'), ('2022-03-01', '2022-03-31'), 
('2022-04-01', '2022-04-30'), ('2022-05-01', '2022-05-31')]
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement