在当前日期添加一年 PYTHON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15741618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:51:20  来源:igfitidea点击:

Add one year in current date PYTHON

pythondate

提问by user2106353

I have fetched a datefrom databasewith the following variable

我已使用以下变量数据库中获取日期

{{ i.operation_date }}

with which I got a value like

我得到了一个像

April 1, 2013

I need to add one year to the above, so that I can get

我需要在上面加上一年,这样我才能得到

April 1, 2014

Please suggest, how can I do this?

请建议,我该怎么做?

回答by MHZ

convert it into python datetime object if it isn't already. then add deltatime

如果尚未将其转换为 python datetime 对象。然后添加增量时间

one_years_later = Your_date + datetime.timedelta(days=(years*days_per_year)) 

for your case days=365.

对于您的案例天数 = 365。

you can have condition to check if the year is leap or no and adjust days accordingly

您可以有条件检查年份是否为闰年并相应地调整天数

you can add as many years as you want

您可以根据需要添加任意数量的年份

回答by ASGM

You can use Python-dateutil'srelativedeltato increment a datetimeobject while remaining sensitive to things like leap years and month lengths. Python-dateutil comes packaged with matplotlib if you already have that. You can do the following:

您可以使用Python-dateutil'srelativedelta来增加datetime对象,同时保持对闰年和月份长度等事物的敏感度。Python-dateutil 与 matplotlib 一起打包,如果你已经有了它。您可以执行以下操作:

from dateutil.relativedelta import relativedelta

new_date = old_date + relativedelta(years=1)

(This answer was given by @Max to a similar question).

(这个答案是@Max 对类似问题给出的)。

But if your date is a string (i.e. not already a datetimeobject) you can convert it using datetime:

但是如果您的日期是一个字符串(即还不是一个datetime对象),您可以使用datetime转换它:

from datetime import datetime
from dateutil.relativedelta import relativedelta

your_date_string = "April 1, 2012"
format_string = "%B %d, %Y"

datetime_object = datetime.strptime(your_date_string, format_string).date()
new_date = datetime_object + relativedelta(years=1)
new_date_string = datetime.strftime(new_date, format_string).replace(' 0', ' ')

new_date_stringwill contain "April 1, 2013".

new_date_string将包含“2013 年 4 月 1 日”。

NB: Unfortunately, datetimeonly outputs day values as "decimal numbers" - i.e. with leading zeros if they're single digit numbers. The .replace()at the end is a workaround to deal with this issue copied from @Alex Martelli(see this questionfor his and other approaches to this problem).

注意:不幸的是,datetime只将天值输出为“十进制数” - 即如果它们是个位数,则带有前导零。将.replace()在年底是处理这个问题从复制解决方法@Alex马尔泰利(见这个问题,这个问题对他和其他方法)。

回答by DrCurrency

It seems from your question that you would like to simply increment the year of your given date rather than worry about leap year implications. You can use the date class to do this by accessing its member year.

从您的问题来看,您似乎只想增加给定日期的年份,而不是担心闰年的影响。您可以使用日期类通过访问其成员年份来执行此操作。

from datetime import date
startDate = date(2012, 12, 21)

# reconstruct date fully
endDate = date(startDate.year + 1, startDate.month, startDate.day)
# replace year only
endDate = startDate.replace(startDate.year + 1)

If you're having problems creating one given your format, let us know.

如果您在创建给定格式时遇到问题,请告诉我们。

回答by Gareth Rees

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

AGSM 的回答显示了使用该python-dateutil包解决此问题的便捷方法。但是如果你不想安装那个包怎么办?你可以像这样在普通 Python 中解决这个问题:

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:

如果您想要另一种可能性(将 2 月 29 日更改为 2 月 28 日),则最后一行应更改为:

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

回答by ArkadiuszG

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

回答by Daniel Margarido

This is what I do when I need to add months or years and don't want to import more libraries. Just create a datetime.date() object, call add_month(date) to add a month and add_year(date) to add a year.

当我需要添加数月或数年并且不想导入更多库时,这就是我所做的。只需创建一个 datetime.date() 对象,调用 add_month(date) 添加一个月和 add_year(date) 添加一年。

import datetime
__author__ = 'Daniel Margarido'


# Check if the int given year is a leap year
# return true if leap year or false otherwise
def is_leap_year(year):
    if (year % 4) == 0:
        if (year % 100) == 0:
            if (year % 400) == 0:
                return True
            else:
                return False
        else:
            return True
    else:
        return False


THIRTY_DAYS_MONTHS = [4, 6, 9, 11]
THIRTYONE_DAYS_MONTHS = [1, 3, 5, 7, 8, 10, 12]

# Inputs -> month, year Booth integers
# Return the number of days of the given month
def get_month_days(month, year):
    if month in THIRTY_DAYS_MONTHS:   # April, June, September, November
        return 30
    elif month in THIRTYONE_DAYS_MONTHS:   # January, March, May, July, August, October, December
        return 31
    else:   # February
        if is_leap_year(year):
            return 29
        else:
            return 28

# Checks the month of the given date
# Selects the number of days it needs to add one month
# return the date with one month added
def add_month(date):
    current_month_days = get_month_days(date.month, date.year)
    next_month_days = get_month_days(date.month + 1, date.year)

    delta = datetime.timedelta(days=current_month_days)
    if date.day > next_month_days:
        delta = delta - datetime.timedelta(days=(date.day - next_month_days) - 1)

    return date + delta


def add_year(date):
    if is_leap_year(date.year):
        delta = datetime.timedelta(days=366)
    else:
        delta = datetime.timedelta(days=365)

    return date + delta


# Validates if the expected_value is equal to the given value
def test_equal(expected_value, value):
    if expected_value == value:
        print "Test Passed"
        return True

    print "Test Failed : " + str(expected_value) + " is not equal to " str(value)
    return False

# Test leap year
print "---------- Test leap year ----------"
test_equal(True, is_leap_year(2012))
test_equal(True, is_leap_year(2000))
test_equal(False, is_leap_year(1900))
test_equal(False, is_leap_year(2002))
test_equal(False, is_leap_year(2100))
test_equal(True, is_leap_year(2400))
test_equal(True, is_leap_year(2016))

# Test add month
print "---------- Test add month ----------"
test_equal(datetime.date(2016, 2, 1), add_month(datetime.date(2016, 1, 1)))
test_equal(datetime.date(2016, 6, 16), add_month(datetime.date(2016, 5, 16)))
test_equal(datetime.date(2016, 3, 15), add_month(datetime.date(2016, 2, 15)))
test_equal(datetime.date(2017, 1, 12), add_month(datetime.date(2016, 12, 12)))
test_equal(datetime.date(2016, 3, 1), add_month(datetime.date(2016, 1, 31)))
test_equal(datetime.date(2015, 3, 1), add_month(datetime.date(2015, 1, 31)))
test_equal(datetime.date(2016, 3, 1), add_month(datetime.date(2016, 1, 30)))
test_equal(datetime.date(2016, 4, 30), add_month(datetime.date(2016, 3, 30)))
test_equal(datetime.date(2016, 5, 1), add_month(datetime.date(2016, 3, 31)))

# Test add year
print "---------- Test add year ----------"
test_equal(datetime.date(2016, 2, 2), add_year(datetime.date(2015, 2, 2)))
test_equal(datetime.date(2001, 2, 2), add_year(datetime.date(2000, 2, 2)))
test_equal(datetime.date(2100, 2, 2), add_year(datetime.date(2099, 2, 2)))
test_equal(datetime.date(2101, 2, 2), add_year(datetime.date(2100, 2, 2)))
test_equal(datetime.date(2401, 2, 2), add_year(datetime.date(2400, 2, 2)))

回答by Siddharth

Another way would be to use pandas "DateOffset" class

另一种方法是使用熊猫“DateOffset”类

link:-https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.tseries.offsets.DateOffset.html

链接:- https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.tseries.offsets.DateOffset.html

Using ASGM's code(above in the answers):

使用 ASGM 的代码(在答案中):

from datetime import datetime
import pandas as pd

your_date_string = "April 1, 2012"
format_string = "%B %d, %Y"

datetime_object = datetime.strptime(your_date_string, format_string).date()
new_date = datetime_object + pd.DateOffset(years=1)

new_date.date()

It will return the the datetime object with the added year.

它将返回添加了年份的日期时间对象。

Something like this:-

像这样的东西:-

datetime.date(2013, 4, 1)