# [Tutor] timedelta doesnt do month

Kent Johnson kent37 at tds.net
Mon Feb 5 20:28:15 CET 2007

```frank h. wrote:
> so what is the easiest way to to get to a list of months in a given
> timeinterval, e.g.
>
>  >> startdate = datetime.date(2005,2,13)
>  >> enddate = datetime.date(2007,1,25)
>  >> delta = enddate - startdate
>  >> delta.days
> 711
>  >> delta.months
> exceptions.AttributeError                            Traceback (most
> recent call last)
> AttributeError: 'datetime.timedelta' object has no attribute 'months'
>
> I want to compute the "monthdifference" and so I can then iterate over
> the months from my startdate to my enddate
> what is the easiest way to accomplish this?

Because of the ambiguities of month arithmetic (what is 2005-1-31 plus
one month?) datetime refuses to guess and does not support this. ("In
the face of ambiguity, refuse the temptation to guess." - The Zen of
Python) The third-party dateutil module is not as circumspect:

In [1]: import datetime

In [2]: startdate = datetime.date(2005,2,13)

In [3]: enddate = datetime.date(2007,1,25)

In [10]: from dateutil.relativedelta import relativedelta

In [11]: delta = relativedelta(months=+1)

In [16]: d = startdate

In [17]: while d <= enddate:
....:     print d
....:     d += delta
....:
....:
2005-02-13
2005-03-13
2005-04-13
2005-05-13
2005-06-13
2005-07-13
2005-08-13
2005-09-13
2005-10-13
2005-11-13
2005-12-13
2006-01-13
2006-02-13
2006-03-13
2006-04-13
2006-05-13
2006-06-13
2006-07-13
2006-08-13
2006-09-13
2006-10-13
2006-11-13
2006-12-13
2007-01-13

http://labix.org/python-dateutil

Kent

```