我有一个以秒为单位返回信息的函数,但我需要以小时:分钟:秒为单位存储该信息。

在Python中是否有一种简单的方法将秒转换为这种格式?


当前回答

使用日期时间:

使用':0>8'格式:

from datetime import timedelta

"{:0>8}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'

"{:0>8}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'

"{:0>8}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'

没有':0>8'格式:

"{}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'

"{}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'

"{}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'

使用时间:

from time import gmtime
from time import strftime

# NOTE: The following resets if it goes over 23:59:59!

strftime("%H:%M:%S", gmtime(125))
# Result: '00:02:05'

strftime("%H:%M:%S", gmtime(60*60*24-1))
# Result: '23:59:59'

strftime("%H:%M:%S", gmtime(60*60*24))
# Result: '00:00:00'

strftime("%H:%M:%S", gmtime(666777))
# Result: '17:12:57'
# Wrong

其他回答

小时(h)秒除以3600(60分钟/小时* 60秒/分钟)

分钟(m)由剩余秒数(小时计算余数,%)除以60(60秒/分钟)计算得出

同样,秒(s)按小时余数和分钟计算。

剩下的只是字符串格式化!

def hms(seconds):
    h = seconds // 3600
    m = seconds % 3600 // 60
    s = seconds % 3600 % 60
    return '{:02d}:{:02d}:{:02d}'.format(h, m, s)

print(hms(7500))  # Should print 02h05m00s

在我的例子中,我想要实现格式 “HH: MM: SS.fff”。 我是这样解决的:

timestamp = 28.97000002861023
str(datetime.fromtimestamp(timestamp)+timedelta(hours=-1)).split(' ')[1][:12]
'00:00:28.970'

通过使用divmod()函数,它只做一个除法就能得到商和余数,你只需要两个数学运算就能很快得到结果:

m, s = divmod(seconds, 60)
h, m = divmod(m, 60)

然后使用字符串格式将结果转换为您想要的输出:

print('{:d}:{:02d}:{:02d}'.format(h, m, s)) # Python 3
print(f'{h:d}:{m:02d}:{s:02d}') # Python 3.6+

你可以使用datetime。timedelta功能:

>>> import datetime
>>> str(datetime.timedelta(seconds=666))
'0:11:06'

dateutil。如果你需要将小时、分钟和秒作为浮点数访问,Relativedelta也很方便。datetime。Timedelta没有提供类似的接口。

from dateutil.relativedelta import relativedelta
rt = relativedelta(seconds=5440)
print(rt.seconds)
print('{:02d}:{:02d}:{:02d}'.format(
    int(rt.hours), int(rt.minutes), int(rt.seconds)))

打印

40.0
01:30:40