Add one year in current date PYTHON

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

I have fetched a date from database with the following variable

{{ i.operation_date }}

8条回答
  •  伪装坚强ぢ
    2020-11-29 02:30

    Look at this:

    #!/usr/bin/python
    
    import datetime
    
    def addYears(date, years):
        result = date + datetime.timedelta(366 * years)
        if years > 0:
            while result.year - date.year > years or date.month < result.month or date.day < result.day:
                result += datetime.timedelta(-1)
        elif years < 0:
            while result.year - date.year < years or date.month > result.month or date.day > result.day:
                result += datetime.timedelta(1)
        print "input: %s output: %s" % (date, result)
        return result
    

    Example usage:

    addYears(datetime.date(2012,1,1), -1)
    addYears(datetime.date(2012,1,1), 0)
    addYears(datetime.date(2012,1,1), 1)
    addYears(datetime.date(2012,1,1), -10)
    addYears(datetime.date(2012,1,1), 0)
    addYears(datetime.date(2012,1,1), 10)
    

    And output of this example:

    input: 2012-01-01 output: 2011-01-01
    input: 2012-01-01 output: 2012-01-01
    input: 2012-01-01 output: 2013-01-01
    input: 2012-01-01 output: 2002-01-01
    input: 2012-01-01 output: 2012-01-01
    input: 2012-01-01 output: 2022-01-01
    

提交回复
热议问题