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

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


当前回答

小时(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

其他回答

你可以用秒除以60得到分钟

import time
seconds = time.time()
minutes = seconds / 60
print(minutes)

再除以60,就得到小时数

小时(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

通过使用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+

有点离题,但可能对某人有用

def time_format(seconds: int) -> str:
    if seconds is not None:
        seconds = int(seconds)
        d = seconds // (3600 * 24)
        h = seconds // 3600 % 24
        m = seconds % 3600 // 60
        s = seconds % 3600 % 60
        if d > 0:
            return '{:02d}D {:02d}H {:02d}m {:02d}s'.format(d, h, m, s)
        elif h > 0:
            return '{:02d}H {:02d}m {:02d}s'.format(h, m, s)
        elif m > 0:
            return '{:02d}m {:02d}s'.format(m, s)
        elif s > 0:
            return '{:02d}s'.format(s)
    return '-'

结果:

print(time_format(25*60*60 + 125)) 
>>> 01D 01H 02m 05s
print(time_format(17*60*60 + 35)) 
>>> 17H 00m 35s
print(time_format(3500)) 
>>> 58m 20s
print(time_format(21)) 
>>> 21s

division = 3623 // 3600 #to hours
division2 = 600 // 60 #to minutes
print (division) #write hours
print (division2) #write minutes

PS:我的代码不专业