[Python] Using datetime.timedelta to add years

Discussão em 'Python' iniciado por Stack, Julho 23, 2025.

  1. Stack

    Stack Membro Participativo

    Given a date, add time interval (X years, X months, X weeks), return date:

    • input args: input_time (datetime.date), interval (datetime.timedelta)
    • return: datetime.date

    I looked at the datetime and datetime.timedelta docs


    class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)¶.
    ​

    These works if I want to add a certain number of hours or weeks. However, I am trying to implement an operation such as date + 1 year:

    start = datetime.datetime(2000, 1, 1)
    # expected output: datetime.datetime(2001, 1, 1)

    # with the weeks, etc arguments given in timedelta, this fails unsurprisingly e.g
    start + datetime.timedelta(weeks = 52)

    # returns datetime.datetime(2000, 12, 30, 0, 0)


    • Is this year-based operation possible with the basic tools of datetime - if so, how?


    • For the year example, I could just do start.replace(year = 2001), but that approach will fail if I have months or weeks as input.


    • The dateutil library seems more advanced, but I was not clear how well it interacts with the in-built datetime objects.

    I reviewed this similar question.

    Running Python 3.6.5 on MacOs.

    Continue reading...

Compartilhe esta Página