减去日期时间对象以获得以毫秒为单位的数值结果 (Python)
Subtract datetime objects to get numerical result in milliseconds (Python)
尝试从包含时间戳且格式为 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(马克·李约瑟的博客)
来自文档的一些解释(链接在上面):
在 8.1.4 datetime
Objects 节中,它指出对于操作:
timedelta = datetime1 - datetime2
(对应于此答案中代码的倒数第二行):
Subtraction of a datetime
from a datetime
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 raise TypeError
尝试从包含时间戳且格式为 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(马克·李约瑟的博客)
来自文档的一些解释(链接在上面):
在 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