# [Python-Dev] Issue5434: datetime.monthdelta

Robert Kern robert.kern at gmail.com
Fri Apr 17 00:29:24 CEST 2009

```On 2009-04-16 17:17, Paul Moore wrote:
> 2009/4/16 Robert Kern<robert.kern at gmail.com>:

>>>>> from dateutil.relativedelta import *
>>>>> dt = relativedelta(months=1)
>>>>> dt
>> relativedelta(months=+1)
>>>>> from datetime import datetime
>>>>> datetime(2009, 1, 15) + dt
>> datetime.datetime(2009, 2, 15, 0, 0)
>>>>> datetime(2009, 1, 31) + dt
>> datetime.datetime(2009, 2, 28, 0, 0)
>>>>> dt.months
>> 1
>>>>> datetime(2009, 1, 31) + relativedelta(years=-1)
>> datetime.datetime(2008, 1, 31, 0, 0)
>
> Yes, but given
>
> r = relativedelta(d1, d2)
>
> how do I determine the number of months between d1 and d2, and the
> "remainder" - what monthmod gives me.

> From the code, r.months looks
> like it works, but it's not documented, and I'm not 100% sure if it's
> always computed.

The result of relativedelta(d1, d2) is the same thing as if it were explicitly
constructed from the years=, months=, etc. keyword arguments. From this example,
I think this is something that can be relied upon:

"""
It works with dates too.

>>> relativedelta(TODAY, johnbirthday)
relativedelta(years=+25, months=+5, days=+11, hours=+12)
"""

> The use case I'm thinking of is converting the difference between 2
> dates into "3 years, 2 months, 5 days" or whatever. I've got an
> application which needs to get this right for one of the dates being
> 29th Feb, so I *really* get to exercise the corner cases :-)

I believe relativedelta() is intended for this use case although it may resolve
ambiguities in a different way than you were hoping.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma