ah bon
ah bon

Reputation: 10021

Create a year month list of specific intervals in Python

How could I create a list of date based on the following condition:

For example, today is 2020-07-01, so I need a list of date contains last month, next 6 month and next 12 month. The expected list will be [2020-06, 2020-12, 2020-06].

Please note I need to use datetime.today() to keep the list dynamically changed.

I have obtained the current month by the code below:

from datetime import datetime
format(datetime.today().strftime('%Y-%m'))

Out:

2020-07

Upvotes: 0

Views: 185

Answers (1)

Leo Arad
Leo Arad

Reputation: 4472

You can use relativedelta to find the diff of the months and a list of the required months.

from datetime import datetime
from dateutil.relativedelta import relativedelta

need_months = [-1, 6, 12]
print([(datetime.today()+ relativedelta(months=i if i < 0 else i - 1)).strftime('%Y-%m') for i in need_months])

Output

['2020-06', '2020-12', '2021-06']

Upvotes: 1

Related Questions