7

So this code what I want:

import datetime
d = datetime.date.today()

three_months_ago = d - timedelta(months=3)

However, as we know, the 'months' param does not exist in timedelta.

I admit I can program like this to achieve the goal:

if d.month > 3:
    three_months_ago = datetime.date(d.year, d.month-3, d.day)
else:
    three_months_ago = datetime.date(d.year-1, d.month-3+12, d.day)

But this seems really stupid...

Can you guys tell me how to realize this smartly?

Mars Lee
  • 1,845
  • 5
  • 17
  • 37
  • You could use [`dateparser`](https://dateparser.readthedocs.org/en/latest/). Have a look at this [answer](http://stackoverflow.com/a/35627268/2932244). – JRodDynamite Mar 10 '16 at 06:11

2 Answers2

15

This could help:

>>>from dateutil.relativedelta import relativedelta
>>>import datetime
>>>datetime.date.today()
datetime.date(2016, 3, 10)
>>>datetime.date.today() - relativedelta(months=3)
datetime.date(2015, 12, 10)

You can use relativedelta() to add or subtract weeks and years too.

0

Numpy's timedelta has months support, ie:

np.timedelta64(3, 'M')

xvan
  • 4,554
  • 1
  • 22
  • 37