我需要在 python 中减去时间增量并以第二种形式返回数字。
我目前有:
from datetime import datetime, timedelta
q1_start_time = datetime.now()
q1_end_time = datetime.now()
total_time = q1_end_time - q1_start_time
print(total_time)
这将返回:
0:00:01.549000
我怎样才能让它只返回 1,或者最好的情况下它会返回 2(向上舍入)。我不需要 0:00:01 只需要 1。
最佳答案
用途:
print(total_time.total_seconds())
自 Python 2.7 起,它可用于 datetime.timedelta
类型的对象。
math.ceil()
用于将 float 舍入到下一个更大/相等的整数。其他舍入函数有 math.floor()
和 round()
。如果只是为了美化数字的打印表示,您还可以使用 Python 的字符串格式化功能,例如
print "elapsed: %.2f seconds" % (t_end-t_start).total_seconds()
供引用:
- http://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds
- http://docs.python.org/2.7/library/functions.html#round
- http://docs.python.org/2/library/math.html#math.ceil
- http://docs.python.org/2/library/math.html#math.floor
- http://docs.python.org/2/library/stdtypes.html#string-formatting-operations
关于python 减去以秒为单位的时间增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22670827/