python-3.x - 减去日期时间对象以获得以毫秒为单位的数值结果(Python)

标签 python-3.x python-datetime

试图找到 已用时间 来自两个包含时间戳且格式为 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 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

关于python-3.x - 减去日期时间对象以获得以毫秒为单位的数值结果(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40444982/

相关文章:

python - 连续数据帧行之间的时间差

python - 使用默认参数传递多个元组

python - 将元素附加到 3 维列表

python-3.x - 套接字错误 : [Errno 49] Can't assign requested address

python - 如何将自然语言中的日期和时间翻译成日期时间?

python - 在 python 3.4 中将字符串日期转换为时间戳

python - 可以从现有日期时间实例创建的自定义日期时间子类?

python - 该日期需要正则表达式模式

django - django 中的自定义身份验证不起作用

python - 使用 CR/LF 对使用正则表达式拒绝匹配