[英]Compute timedelta between two datetime.time instances
I'm trying to create a task manager with a spcefic time&task, while the date is irrelevant ( everyday reccurance ). 我正在尝试创建一个具有特定时间和任务的任务管理器,而日期却无关紧要(日常事务)。
I'm trying to find the diff between times, eg timedelta(hours=1)
: 我试图找到时间之间的差异,例如
timedelta(hours=1)
:
datetime.time(13,00,00) - datetime.time(14,00,00)
ended with failture: 以失败告终:
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'
while datetime.date(2017,06,26) - datetime.date(2017,06,25)
ends well. 而
datetime.date(2017,06,26) - datetime.date(2017,06,25)
结束得很好。
Python's datetime
module doesn't let you calculate time deltas based on time-of-day only. Python的
datetime
模块不允许您仅基于一天中的时间来计算时间增量。 That can result in ambiguities such as what to do when a sum is greater than 24 hours. 这可能导致歧义,例如总和大于24小时时该怎么办。 In your case there is a hack that should work.
在您的情况下,应该可以使用一种hack。 Turn your times into
datetime
on the same day and do the math from there. 将您的时间转换为同一天的
datetime
时间,然后从那里进行数学运算。
>>> def time_diff(t1, t2):
... today = datetime.date.today()
... return (datetime.datetime.combine(today, t1)
... - datetime.datetime.combine(today, t2))
...
>>>
>>> time_diff(datetime.time(13,0,0), datetime.time(14,0,0))
datetime.timedelta(-1, 82800)
Negative timedelta
looks weird (that's -1 days plus 82800 seconds) but should work in other calculations. 负
timedelta
看起来很奇怪(即-1天加上82800秒),但应该在其他计算中起作用。
要在几秒钟内获得答案,请按如下所示修改您的代码:
return (datetime.datetime.combine(today, t1)-datetime.datetime.combine(today, t2)).total_seconds()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.