How to add one month to datetime?

dellaq at ml1.net dellaq at ml1.net
Fri Oct 21 21:26:00 EDT 2005


Bengt Richter wrote:
> The OP will still have to decide whether he likes the semantics ;-)
> E.g., what does he really want as the date for "one month" after January 30 ?
>
> Regards,
> Bengt Richter

When dealing with bonds a common convention is to return the same day
in the succeeding month if it is valid otherwise return the last day of
that month. However, if the original date is the last day of the month,
then the last day of the succeeding month should always be returned.

This snippet adds an arbitrary number of months (positive or negative)
according to that convention.

OneDay = datetime.timedelta(days=1)

def addMonth(date, n=1):
    # add n+1 months to date then subtract 1 day
    # to get eom, last day of target month
    q,r = divmod(date.month+n, 12)
    eom = datetime.date(date.year+q, r+1, 1) - OneDay
    if date.month != (date+OneDay).month or date.day >= eom.day:
        return eom
    return eom.replace(day=date.day)

Regards,
John Dell'Aquila




More information about the Python-list mailing list