在Python中添加年份 [英] Adding years in python

查看:308
本文介绍了在Python中添加年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想在程序中添加100年,为什么显示错误的日期?

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()


推荐答案

一年中的秒数不固定想知道一年中有多少天吗?再想一想。

要执行周期(日历)算法,可以使用 dateutil.relativedelta

To perform period (calendar) arithmetic, you could use dateutil.relativedelta:

#!/usr/bin/env python
from datetime import date
from dateutil.relativedelta import relativedelta # $ pip install python-dateutil

print(date(1920, 1, 10) + relativedelta(years=+100))
# -> 2020-01-10

要理解,为什么 d.replace(year = d.year + 100)失败,请考虑:

To understand, why d.replace(year=d.year + 100) fails, consider:

print(date(2000, 2, 29) + relativedelta(years=+100))
2100-02-28

2100 不是a年,而 2000 是a年。

Notice that 2100 is not a leap year while 2000 is a leap year.

如果要添加的唯一单位是year,则可以仅使用stdlib来实现:

If the only units you want to add is year then you could implement it using only stdlib:

from calendar import isleap

def add_years(d, years):
    new_year = d.year + years
    try:
        return d.replace(year=new_year)
    except ValueError:
        if (d.month == 2 and d.day == 29 and # leap day
            isleap(d.year) and not isleap(new_year)):
            return d.replace(year=new_year, day=28)
        raise

示例:

from datetime import date

print(add_years(date(1920, 1, 10), 100))
# -> 2020-01-10
print(add_years(date(2000, 2, 29), 100))
# -> 2100-02-28
print(add_years(date(2000, 2, 29), 4))
# -> 2004-02-29

这篇关于在Python中添加年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆