Python 从时间间隔中获取小时、分钟和秒

0 投票
1 回答
2038 浏览
提问于 2025-04-18 11:57

我有一些时间戳,它们是通过给定的时间间隔计算出来的。例如,时间戳是 193894,时间间隔是 20000。计算时间的方法是 193894/20000 = 9.6947。这里的 9.6947 表示 9分钟,而 0.6947 分钟转换成秒就是 (0.6947 * 60) = 42秒(四舍五入),所以人类可读的时间戳就是 9分钟42秒

我在想,是否有一种更“Pythonic”的方法(假设有某个库可以用)来处理这个,而不是对每个时间戳都进行这种繁琐的数学计算呢?

原因是,如果时间戳是 1392338(也就是 1小时9分钟37秒),我希望能够保持动态变化。

我只是想知道,是否有比这种数学计算更好的方法来处理这个问题。

1 个回答

2

这个相关的问题可以帮助你在获得timedelta对象后进行格式化,但为了达到你想要的具体效果,你需要做一些调整。

from __future__ import division

from datetime import timedelta
from math import ceil

def get_interval(timestamp, interval):
    # Create our timedelta object
    td = timedelta(minutes=timestamp/interval)
    s = td.total_seconds()
    # This point forward is based on http://stackoverflow.com/a/539360/2073595
    hours, remainder = divmod(s, 3600)
    minutes = remainder // 60
    # Use round instead of divmod so that we'll round up when appropriate.
    # To always round up, use math.ceil instead of round.
    seconds = round(remainder - (minutes * 60))
    return "%d hours %d min %d sec" % (hours, minutes, seconds)

if __name__ == "__main__:
    print print_interval(1392338, 20000)
    print get_interval(193894, 20000)

输出结果:

1 hours 9 min 37 sec
0 hours 9 min 42 sec

撰写回答