Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7 Get month from 2 months ago (i.e get '05' from todays date)

I'm sure there is an easy way to do this that I have missed with my efforts to find the answer.

Basically how do I get the number of month i.e '05' or '04' from n number of months ago?

Apologies if this was already answered but the questions I researched here could not answer my question.

Edit

There is no month parameter in timedelta, so this did not answer my question.

Martin answered my question perfectly!

like image 899
Andy Feely Avatar asked Dec 20 '22 01:12

Andy Feely


1 Answers

With some simple modular arithmetic:

from datetime import date

def months_ago(count):
    today = date.today()
    return ((today.month - count - 1) % 12) + 1

Demo:

>>> date.today()
datetime.date(2015, 7, 28)
>>> for i in range(13):
...     print(months_ago(i))
... 
7
6
5
4
3
2
1
12
11
10
9
8
7
like image 82
Martijn Pieters Avatar answered Dec 26 '22 10:12

Martijn Pieters