【发布时间】:2020-08-23 07:19:39
【问题描述】:
我试图从我的字典中找出两个转换后的时间字符串之间的区别。我已经使用 strptime() 将字符串从“历史值”转换为日期时间对象,但是当我从另一个中减去一个时,我得到了一个 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)
我收到的输出是:
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'
最诚挚的问候,
安德鲁
【问题讨论】:
-
difference_in_time = associated_time1.gettime() - associated_time2.gettime() 将以毫秒为单位提供差异。
-
'datetime.time' 没有属性 gettime。最好将其保留为 datetime.datetime 吗?
-
是的,我的方法假定一个 Date 对象。
标签: python datetime time types subtraction