pythondatetimepython-3.xpython-datetime

Adding years in python


If I want to add 100 years in my program, why is it showing the wrong date?

import datetime
stringDate= "January 10, 1920"
dateObject= datetime.datetime.strptime(stringDate, "%B %d, %Y")
endDate= dateObject+datetime.timedelta(days=100*365)
print dateObject.date()
print endDate.date()

Solution

  • You can't just add 100 * 365 days, because there are leap years with 366 days in that timespan. Over your 100 year span you are missing 25 days.

    Better to just use the datetime.replace() method here:

    endDate = dateObject.replace(year=dateObject.year + 100)
    

    This can still fail for February 29th in a leap year, as depending on the number of years you add you'd end up with an invalid date. You could move back to February 28th in that case, or use March 31st; handle the exception thrown and switch to your chosen replacement:

    years = 100
    try:
        endDate = dateObject.replace(year=dateObject.year + years)
    except ValueError:
        # Leap day in a leap year, move date to February 28th
        endDate = dateObject.replace(year=dateObject.year + years, day=28)
    

    Demo:

    >>> import datetime
    >>> dateObject = datetime.datetime(1920, 1, 10, 0, 0)
    >>> dateObject.replace(year=dateObject.year + 100)
    datetime.datetime(2020, 1, 10, 0, 0)