【问题标题】:How could I display a time difference in python in total "hours:minutes:seconds"?如何在 python 中显示总“小时:分钟:秒”的时差?
【发布时间】:2017-01-19 17:39:05
【问题描述】:

在 Python 中,我使用 datetime.datetime.now() 检索了开始时间和结束时间。我想将任何微秒四舍五入到最接近的秒数并将天数转换为小时数。时差的最终显示格式应为"hours:minutes:seconds"。提前感谢您的帮助!

【问题讨论】:

  • 减去两个datetimes 将得到一个timedelta,考虑到该对象的属性,这很容易。

标签: python time difference


【解决方案1】:

没有直接的方法可以按照您的意愿格式化timedelta 对象,因此您必须自己进行计算:

    delta = end - start
    seconds = int(round(delta.total_seconds()))
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    print("{:d}:{:02d}:{:02d}".format(hours, minutes, seconds))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 2023-01-07
    • 1970-01-01
    相关资源
    最近更新 更多