Add one year in current date PYTHON

后端 未结 8 1497
别跟我提以往
别跟我提以往 2020-11-29 01:59

I have fetched a date from database with the following variable

{{ i.operation_date }}

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 02:22

    AGSM's answer shows a convenient way of solving this problem using the python-dateutil package. But what if you don't want to install that package? You could solve the problem in vanilla Python like this:

    from datetime import date
    
    def add_years(d, years):
        """Return a date that's `years` years after the date (or datetime)
        object `d`. Return the same calendar date (month and day) in the
        destination year, if it exists, otherwise use the following day
        (thus changing February 29 to March 1).
    
        """
        try:
            return d.replace(year = d.year + years)
        except ValueError:
            return d + (date(d.year + years, 1, 1) - date(d.year, 1, 1))
    

    If you want the other possibility (changing February 29 to February 28) then the last line should be changed to:

            return d + (date(d.year + years, 3, 1) - date(d.year, 3, 1))
    

提交回复
热议问题