Andy Feely
Andy Feely

Reputation: 265

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!

Upvotes: 4

Views: 748

Answers (2)

n8yoder
n8yoder

Reputation: 10006

While Martijn's answer is perfect for your specific question for anyone who stumbles across this answer looking for a date X months ago rather than just the month's number I would suggest using relativedelta from the third party module dateutil. I have found it quite helpful:

>>> from datetime import date
>>> from dateutil.relativedelta import relativedelta

>>> today = date.today()
datetime.date(2015, 7, 28)

>>> for i in range(13):
        print(today - relativedelta(months=i))
2015-07-28
2015-06-28
2015-05-28
2015-04-28
2015-03-28
2015-02-28
2015-01-28
2014-12-28
2014-11-28
2014-10-28
2014-09-28
2014-08-28
2014-07-28

Upvotes: 4

Martijn Pieters
Martijn Pieters

Reputation: 1124208

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

Upvotes: 7

Related Questions