[英]Adding timedelta object to datetime
My timedelta object looks like this: txdelta = 00:30:00
. 我的timedelta对象看起来像这样: txdelta = 00:30:00
。 I want to add it to a datetime object but it consistently isn't working: 我想将其添加到datetime对象,但始终无法正常工作:
from datetime import datetime, date, time, timedelta
localdt = datetime.combine(datetime.strptime('2015-06-18', '%Y-%m-%d').date(),
(23:35:02+timedelta(txdelta)).time())
Note that the 23:35:02
is already a datetime object. 请注意, 23:35:02
:02已经是日期时间对象。 I get this error message: 我收到此错误消息:
TypeError: unsupported type for timedelta days component: datetime.timedelta
What am I doing wrong? 我究竟做错了什么?
The way you create your time
object is strange. 创建time
对象的方式很奇怪。 I strongly advice you to declare it this way if you're not used to it: 如果您不习惯使用它,我强烈建议您以这种方式声明它:
txdelta = timedelta(minutes=30)
tdelta = time(hour=1, minute=35, second=2)
If I got it well you tried to combine a date
, a time
and a timedelta
. 如果我做得好,你会尝试将date
, time
和timedelta
结合在一起。 The full code below should do the trick: 下面的完整代码应该可以解决问题:
from datetime import datetime, date, time, timedelta
txdelta = timedelta(minutes=30)
tdelta = time(hour=1, minute=35, second=2)
localdt = datetime.combine(datetime.strptime('2015-06-18', '%Y-%m-%d').date(), tdelta) + txdelta
print(localdt)
Basically, you combine a datetime object with a time one, and you simply add the timedelta object afterwards. 基本上,您将一个datetime对象与一个时间对象组合在一起,然后简单地添加timedelta对象。
The output is: 输出为:
2015-06-18 02:05:02
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.