如何在今年从Python开始打印 [英] How to Print next year from current year in Python
问题描述
如果使用最简单的代码在python中给出当前年份,则可以打印下一年,可能在一行中使用datetime模块。
How can I print the next year if the current year is given in python using the simplest code, possibly in one line using datetime module.
推荐答案
date和datetime对象都有一个年份
属性,一个号码。只需添加1:
Both date and datetime objects have a year
attribute, which is a number. Just add 1:
>>> from datetime import date
>>> print date.today().year + 1
2013
如果你有当年在一个变量中,只需直接添加1,不需要麻烦datetime模块:
If you have the current year in a variable, just add 1 directly, no need to bother with the datetime module:
>>> year = 2012
>>> print year + 1
2013
如果您的日期是字符串,只需选择代表年份的4位数字并将其传递给 int
:
If you have the date in a string, just select the 4 digits that represent the year and pass it to int
:
>>> date = '2012-06-26'
>>> print int(date[:4]) + 1
2013
年算术非常简单,使其成为一个整数,只需添加1.它不会比这更简单。
Year arithmetic is exceedingly simple, make it an integer and just add 1. It doesn't get much simpler than that.
但是,如果您正在使用整个日期,而您需要同一天,但一年后,使用组件创建一个新的日期
对象,年增加1:
If, however, you are working with a whole date, and you need the same date but one year later, use the components to create a new date
object with the year incremented by one:
>>> today = date.today()
>>> print date(today.year + 1, today.month, today.day)
2013-06-26
,或者您可以使用 .replace
函数,该函数返回您指定的字段更改的副本:
or you can use the .replace
function, which returns a copy with the field you specify changed:
>>> print today.replace(year=today.year + 1)
2013-06-26
请注意,当今天的今天是在2月29日的闰年,这可能会有点棘手。因此,绝对的,故障安全的正确方法是这样工作的:
Note that this can get a little tricky when today
is February 29th in a leap year. The absolute, fail-safe correct way to work this one is thus:
def nextyear(dt):
try:
return dt.replace(year=dt.year+1)
except ValueError:
# February 29th in a leap year
# Add 365 days instead to arrive at March 1st
return dt + timedelta(days=365)
这篇关于如何在今年从Python开始打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!