在巨蟒中减去两倍

我有两个 datetime.time值,exitenter,我想这样做:

duration = exit - enter

然而,我得到了这个错误:

TypeError:-: ‘ datetime.time’和 日期时间

我该怎么做才正确呢?一个可能的解决方案是将 time变量转换为 datetime变量,然后进行减法,但我相信你们一定有一个更好和更干净的方法。

217481 次浏览

datetime.time不支持这一点,因为以这种方式减去时间几乎毫无意义。如果你想这样做,使用一个完整的 datetime.datetime

试试这个:

from datetime import datetime, date


datetime.combine(date.today(), exit) - datetime.combine(date.today(), enter)

combine构建一个可以减去的日期时间。

import datetime


def diff_times_in_seconds(t1, t2):
# caveat emptor - assumes t1 & t2 are python times, on the same day and t2 is after t1
h1, m1, s1 = t1.hour, t1.minute, t1.second
h2, m2, s2 = t2.hour, t2.minute, t2.second
t1_secs = s1 + 60 * (m1 + 60*h1)
t2_secs = s2 + 60 * (m2 + 60*h2)
return( t2_secs - t1_secs)


# using it
diff_times_in_seconds( datetime.datetime.strptime( "13:23:34", '%H:%M:%S').time(),datetime.datetime.strptime( "14:02:39", '%H:%M:%S').time())

不要用时间,试试 timedelta:

from datetime import timedelta


t1 = timedelta(hours=7, minutes=36)
t2 = timedelta(hours=11, minutes=32)
t3 = timedelta(hours=13, minutes=7)
t4 = timedelta(hours=21, minutes=0)


arrival = t2 - t1
lunch = (t3 - t2 - timedelta(hours=1))
departure = t4 - t3


print(arrival, lunch, departure)

我也遇到过类似的情况,我们最终使用了名为 箭头的外部库。

它看起来是这样的:

>>> import arrow
>>> enter = arrow.get('12:30:45', 'HH:mm:ss')
>>> exit = arrow.now()
>>> duration = exit - enter
>>> duration
datetime.timedelta(736225, 14377, 757451)

用途:

from datetime import datetime, date


duration = datetime.combine(date.min, end) - datetime.combine(date.min, beginning)

使用 date.min比较简洁,即使在午夜也能工作。

如果第一个调用发生在23:59:59,而下一个调用发生在00:00:00,那么 date.today()可能会返回意想不到的结果。

Python时间三角洲库应该可以满足您的需要。当您减去两个 datetime实例时,返回一个 timedelta

import datetime
dt_started = datetime.datetime.utcnow()


# do some stuff


dt_ended = datetime.datetime.utcnow()
print((dt_ended - dt_started).total_seconds())

您有两个 datetime.time 对象,因此您只需使用 datetime.timedetla 创建两个 timedelta,然后使用“-”操作数创建 subtract。下面是不使用 datetime 进行两次减法的示例方法。

enter = datetime.time(hour=1)  # Example enter time
exit = datetime.time(hour=2)  # Example start time
enter_delta = datetime.timedelta(hours=enter.hour, minutes=enter.minute, seconds=enter.second)
exit_delta = datetime.timedelta(hours=exit.hour, minutes=exit.minute, seconds=exit.second)
difference_delta = exit_delta - enter_delta

Different _ delta 是您可以根据自己的理由使用的差异。

datetime.time不能做到这一点-但你可以使用 datetime.datetime.now()

start = datetime.datetime.now()
sleep(10)
end = datetime.datetime.now()
duration = end - start

timedelta接受负(-)时间值。所以它可以简单如下。

回答(单行)

datetime.timedelta(hours=exit.hour-enter.hour, minutes=exit.minute-enter.minute)

运行测试

import datetime


enter = datetime.time(hour=1, minute=30)
exit = datetime.time(hour=2, minute=0)
duration = datetime.timedelta(hours=exit.hour-enter.hour, minutes=exit.minute-enter.minute)


>>> duration
datetime.timedelta(seconds=1800)
import time
from datetime import datetime


def calcTime(enter,exit):
format="%H:%M:%S"
#Parsing the time to str and taking only the hour,minute,second
#(without miliseconds)
enterStr = str(enter).split(".")[0]
exitStr = str(exit).split(".")[0]
#Creating enter and exit time objects from str in the format (H:M:S)
enterTime = datetime.strptime(enterStr, format)
exitTime = datetime.strptime(exitStr, format)
return exitTime - enterTime


enter = datetime.today().time()
#Sleeping for 5 seconds before initializing the exit variable
time.sleep(5)
exit = datetime.today().time()
duration = calcTime(enter,exit)
print(f"Duration is {duration} (Hours:Minutes:Seconds)")
#Output: Duration is 0:00:05 (Hours:Minutes:Seconds)

如果有帮助,可以使用如下所示的 calcTime 函数。