试图找到 已用时间 来自两个包含时间戳且格式为 hh:mm:ss.mss
的字符串.基本上,我想减去两个 datetime
对象并在 中获得数值结果毫秒 .
这是我的代码:
from datetime import datetime
elapsed_time = 0
s = '13:46:34.550'
e = '13:46:36.750'
# only interested on the time part, not the date
start_time = datetime.strptime(s, '%H:%M:%S.%f')
end_time = datetime.strptime(e, '%H:%M:%S.%f')
#elapsed_time = end_time - start_time
#elapsed_time = (end_time - start_time).microsecond
对于两者
elapsed_time
计算我得到一个 TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'int'
.它应该打印
00:00:02.250
或(理想情况下)2200
.任何想法我做错了什么?
最佳答案
以下对我有用(使用 Python 3.5.2):
from datetime import datetime
elapsed_time = 0
s = '13:46:34.550'
e = '13:46:36.750'
# only interested on the time part, not the date
start_time = datetime.strptime(s, '%H:%M:%S.%f')
end_time = datetime.strptime(e, '%H:%M:%S.%f')
diff = end_time - start_time
elapsed_time = int((diff.seconds * 1000) + (diff.microseconds / 1000))
我得到的输出是
2200
这是 s
之间的时间差(以毫秒为单位)和 e
一些引用:
Python: Difference between two datetimes in milliseconds (马克尼达姆的博客)
Python docs about datetime
来自文档的一些解释(链接在上面):
在 8.1.4
datetime
Objects 部分,它指出对于操作:timedelta = datetime1 - datetime2
(对应于本答案中的最后第二行代码):
Subtraction of a
datetime
from adatetime
is defined only if both operands are naive, or if both are aware. If one is aware and the other is naive,TypeError
is raised.
还:
Changed in version 3.3: Equality comparisons between naive and aware
datetime
instances don’t raiseTypeError
关于python-3.x - 减去日期时间对象以获得以毫秒为单位的数值结果(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40444982/