Home > Enterprise >  How to get last date of the previous 9 months in python
How to get last date of the previous 9 months in python

Time:11-18

Here I need to get the previous 9 months last date when we provide year and quarter as a input.

Input to my program is year and quarter

Example:

year = 2022
quarter = 'Q3' 

Expected output

2022-06-30
2022-05-30
2022-04-30
2022-03-31
2022-02-28
2022-01-31
2021-12-31
2021-11-30
2021-10-31

Is there any way to achieve this in python it would be great.

CodePudding user response:

You can use date_range:

year = 2022
quarter = 'Q3'

pd.Series(pd.date_range(end=pd.Timestamp(f'{year}-{quarter}'), periods=9, freq='1M')[::-1])

Output:

0   2022-06-30
1   2022-05-31
2   2022-04-30
3   2022-03-31
4   2022-02-28
5   2022-01-31
6   2021-12-31
7   2021-11-30
8   2021-10-31
dtype: datetime64[ns]
  • Related