[Tutor] timedelta doesnt do month

Kent Johnson kent37 at tds.net
Tue Feb 6 12:08:57 CET 2007


Alan Gauld wrote:
> "Kent Johnson" <kent37 at tds.net> wrote
> 
>> Because of the ambiguities of month arithmetic (what is 2005-1-31 
>> plus
>> one month?) datetime refuses to guess and does not support this.
> 
>> The third-party dateutil module is not as circumspect:
>>
>> In [1]: import datetime
>>
>> In [2]: startdate = datetime.date(2005,2,13)
> 
> As a matter of interest what would dateutil do with
> the example above?

It coerces the day to fall within the month:

In [1]: import datetime

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

In [3]: from dateutil.relativedelta import relativedelta

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

In [5]: startdate+delta
Out[5]: datetime.date(2005, 2, 28)

Details here:
http://labix.org/python-dateutil#head-72c4689ec5608067d118b9143cef6bdffb6dad4e

Kent



More information about the Tutor mailing list