python - 在python中减去两次

标签 python python-2.7

我的代码有问题。我试图减去两次,但它给了我一个错误:

TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'time.struct_time'

错误在这条线上跳跃:
diff = (end_dt - start_dt)

当我尝试这个时:
start = "09:35:23"
end = "10:23:00"
start_dt = time.strptime(start, '%H:%M:%S')
end_dt = time.strptime(end, '%H:%M:%S')
diff = (end_dt - start_dt)

你能帮我解决我遇到的错误吗?

最佳答案

您需要使用 datetime模块:

import datetime

start = "09:35:23"
end = "10:23:00"
start_dt = datetime.datetime.strptime(start, '%H:%M:%S')
end_dt = datetime.datetime.strptime(end, '%H:%M:%S')
diff = (end_dt - start_dt)
print(diff)

输出
datetime.timedelta(0, 2857)

这会生成两个 datetime对象,start_dtend_dt .当您从另一个中减去一个时,它会返回 timedelta .

关于python - 在python中减去两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34744613/

相关文章:

python - Django 使用字符串来过滤模型以避免重复

python - 禁用 python 记录器输出

python - Jupyter notebook 选择旧版本的 numpy

python - 值错误: could not convert string to float: 'r'

python - 将多维数组中的 0 更改为 x

python - 使用 Python boto 从 S3 获取文件元数据

python - 从矩阵创建随机数组

python-2.7 - 从 crontab 运行 python 脚本时的编码问题

php - 批量 HTTP 状态请求

Python Popen - 等待与通信与 CalledProcessError