Print last N year-month format of dates with Python

Question:

I want to get list of last N year-month elements (strings).
For example, it is October now (10th month), and I want to get last 3 months, my example result would be:

["2022-10", "2022-09", "2022-08"]

I know how to get current month and year:

import datetime
from datetime import date

todays_date = datetime.date.today()
year = str(todays_date.year)
month = str(todays_date.month) 

print(year, month)

But I do not know how to write a function that will give me last N (2,3,4,6,7,…) months.

The biggest problem is for example month of February, thats second month, and I want to get the last 4 months, the year also needs to update.

Asked By: taga

||

Answers:

Use the timedelta function. Using your code, it would look something like this. n is how far back you want to go.

import datetime

n = 3 #howmany months back you want to go
todays_date = datetime.date.today()
print(todays_date.year, todays_date.month)

for i in range(1,n):
    todays_date-=datetime.timedelta(days=30)
    print(todays_date.year, todays_date.month)


The output is,

2022 10
2022 9
2022 8

Of course there are more elegant ways to do this. You can make a dictionary of howmany days are in each month because some months have 30, 31, 29 and 28 days, so maybe if you go back many years you might get something wrong.

You could also instead just take the year and month, and minus off 1 every loop.

Then when month reaches 1, reduce the year by 1 and reset the month to 12.

import datetime

n = 14
today = datetime.date.today()

def months_back (today, months):
    year = int(today.year)
    month = int(today.month)

    for i in range(months):
        print(year,month)
        if month != 1:
            month -= 1
        else:
            year-=1
            month=12

months_back(todays_date, 3)

This function does what I described above. It treats the month and years as integers.

Answered By: anarchy

Here is one way of doing it. Simply counting it down in a for loop.

import datetime
from datetime import date


def nMonthsBack(year, month, n):
    # Find correct year by seeing how many years back we go
    t = month -n -1
    t = t//12
    year = year + t
    # Count down months
    n = n%12
    for i in range(n):
        if (month == 1):
            month = 12
        else:
            month = month -1
    
    return year, month


todays_date = datetime.date.today()

year, month = nMonthsBack(todays_date.year, todays_date.month, 155)
print(str(year), str(month))
Answered By: user3328152

You can use timedelte,

def last_n_months(n):
    start_date = datetime.date.today() - timedelta(days=n*30)
    delta = datetime.date.today() - start_date
    return set([(start_date + timedelta(days=i)).strftime("%Y-%m") for i in range(delta.days + 1)])

Execution:

In [1]: last_n_months(5)
Out[1]: {'2022-05', '2022-06', '2022-07', '2022-08', '2022-09', '2022-10'}
Answered By: Rahul K P

Solution:

import datetime

def last_n_months(N):
    today = datetime.date.today()
    months = []
    for n in range(N):
        month_diff = today.month - n
        years, month = divmod(month_diff, 12) if month_diff % 12 else ((month_diff//12) - 1, 12)
        months.append(str(today.year + years) + "-" + (2 - len(str(month)) )*"0" + str(month))
    return months
    
last_n_months(11)

Output:

['2022-10',
 '2022-09',
 '2022-08',
 '2022-07',
 '2022-06',
 '2022-05',
 '2022-04',
 '2022-03',
 '2022-02',
 '2022-01',
 '2021-12']
Answered By: Timo
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.