使用datetime.timedelta添加年份 [英] Using datetime.timedelta to add years
问题描述
我正在用Python做一些时间计算。
I am doing some time calculations in Python.
部分原因是:
给出日期,添加时间间隔(X年,X个月,X周),返回日期
即
- 输入参数:input_time(datetime.date),间隔(datetime.timedelta)
- 返回:datetime.date
我查看了日期时间和 datetime.timedelta文档
class datetime.timedelta(天= 0,秒= 0,微秒= 0,毫秒= 0,分钟= 0,小时= 0,星期= 0)¶
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)¶.
如果我想增加一定数量的小时数或星期数,这些方法效果很好。但是,
These seem to work well if I want to add a certain number of hours or weeks. However,
- 我正在尝试执行以下操作 date + 1 year 并且无法弄清楚
- I am trying to implement an operation such as date + 1 year and can't figure it out
例如
start = datetime.datetime(2000, 1, 1)
# expected output: datetime.datetime(2001, 1, 1)
# with the weeks, etc arguments given in timedelta, this fails unsurprisingly e.g
start + datetime.timedelta(weeks = 52)
# returns datetime.datetime(2000, 12, 30, 0, 0)
< h3>问题
-
使用日期时间的基本工具是否可以进行今年的操作-如果是这样,我将如何处理
Question
Is this year-based operation possible with the basic tools of datetime - if so, how would I go about it?
我意识到,对于年份示例,我可以执行
start.replace(year = 2001)
,但是如果输入几个月或几周,该方法将失败。I realize that for the year example, I could just do
start.replace(year = 2001)
, but that approach will fail if I have months or weeks as input.据我所知, dateutil 库具有更高级的功能,但我不清楚它与in-建立日期时间对象。
From my understanding, the dateutil library has more advanced features, but I was not clear how well it interacts with the in-built datetime objects.
我已经审查过类似的问题,但这并没有帮助我。
I have reviewed this similar question but it did not help me with this.
任何帮助深表感谢!
在MacO上运行Python 3.6.5。
Running Python 3.6.5 on MacOs.
推荐答案
timedelta
不支持年份,因为一年的持续时间取决于哪一年(对于例如,leap年有2月29日)。timedelta
does not support years, because the duration of a year depends on which year (for example, leap years have Feb 29).您可以改用
relativedelta
,它支持年
,并考虑了添加的基准日期:You could use a
relativedelta
instead, which does supportyears
and takes into account the baseline date for additions:>>> from dateutil.relativedelta import relativedelta >>> now = datetime.now() >>> now datetime.datetime(2019, 1, 27, 19, 4, 11, 628081) >>> now + relativedelta(years=1) datetime.datetime(2020, 1, 27, 19, 4, 11, 628081)
这篇关于使用datetime.timedelta添加年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!