Python 如何减去日期时间对象?

Python 如何减去日期时间对象?,python,datetime,time,types,subtraction,Python,Datetime,Time,Types,Subtraction,我试图从字典中找出两个转换后的时间字符串之间的差异。我已经使用strtime()将字符串从“历史值”转换为datetime对象,但是当我从一个字符串中减去另一个字符串时,会得到一个TypeError from datetime import datetime low_end_value = 50.00 stockDict = {'Historic value': [('16:00:00:00', 55.50), ("15:00:00:00", 45.50), ("14:00:00:00"

我试图从字典中找出两个转换后的时间字符串之间的差异。我已经使用strtime()将字符串从“历史值”转换为datetime对象,但是当我从一个字符串中减去另一个字符串时,会得到一个TypeError

from datetime import datetime


low_end_value = 50.00

stockDict = {'Historic value': [('16:00:00:00', 55.50), ("15:00:00:00", 45.50), 
("14:00:00:00", 75.50), ("13:00:00:00", 65.50), ("12:00:00:00", 55.50)]}

x = 0
while (stockDict['Historic value'][x][1]) > low_end_value:

   if (stockDict['Historic value'][x][1]) < low_end_value:
       break
   x += 1

date_str1 = (stockDict['Historic value'][(x - 1)][0])
# (n-1)th historical time

date_str2 = (stockDict['Historic value'][x][0])
# (n)th historical time

associated_time1 = (datetime.strptime(date_str1, '%H:%M:%S:%f').time())
# converted to a datetime object

associated_time2 = (datetime.strptime(date_str2, '%H:%M:%S:%f').time())
# converted to a datetime object

difference_in_time = associated_time1 - associated_time2

print(difference_in_time)
从日期时间导入日期时间
低端值=50.00
stockDict={‘历史价值’:[('16:00:00',55.50),('15:00:00',45.50),
("14:00:00:00", 75.50), ("13:00:00:00", 65.50), ("12:00:00:00", 55.50)]}
x=0
而(stockDict[‘历史价值’][x][1])>低端价值:
如果(stockDict['Historical value'][x][1])<下限值:
打破
x+=1
日期_str1=(stockDict[‘历史价值’][(x-1)][0])
#(n-1)历史时间
日期_str2=(stockDict['历史价值][x][0])
#(n)历史时间
关联的_time1=(datetime.strtime(date_str1,'%H:%M:%S:%f').time())
#已转换为datetime对象
关联的_-time2=(datetime.strtime(date_-str2,'%H:%M:%S:%f').time())
#已转换为datetime对象
时间差=关联的时间1-关联的时间2
打印(时间差)
我收到的输出是:

Traceback (most recent call last):
 File "C:/Users/engli/PycharmProjects/Calculated time.py", line 47, in <module>
   difference_in_time = associated_time1 - associated_time2
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'
回溯(最近一次呼叫最后一次):
文件“C:/Users/engli/PycharmProjects/Calculated time.py”,第47行,在
时间差=关联的时间1-关联的时间2
TypeError:-:“datetime.time”和“datetime.time”的操作数类型不受支持
最亲切的问候

Andrew

尝试使用datetime.combine()方法


差异_in_time=associated_time1.gettime()-associated_time2.gettime()将以毫秒为单位给出差异。“datetime.time”没有属性gettime。最好将其保留为datetime.datetime?是的,我的方法假定为Date对象。
from datetime import datetime, date
datetime.combine(date.min, associated_time1) - datetime.combine(date.min, associated_time2)