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

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


当前回答

我看了这里的每一个答案,仍然尝试自己的答案

def a(t):
  print(f"{int(t/3600)}H {int((t/60)%60) if t/3600>0 else int(t/60)}M {int(t%60)}S")

结果:

>>> a(7500)
2H 5M 0S
>>> a(3666)
1H 1M 6S

Python: 3.8.8

其他回答

我是这样得到它的。

def sec2time(sec, n_msec=3):
    ''' Convert seconds to 'D days, HH:MM:SS.FFF' '''
    if hasattr(sec,'__len__'):
        return [sec2time(s) for s in sec]
    m, s = divmod(sec, 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)
    if n_msec > 0:
        pattern = '%%02d:%%02d:%%0%d.%df' % (n_msec+3, n_msec)
    else:
        pattern = r'%02d:%02d:%02d'
    if d == 0:
        return pattern % (h, m, s)
    return ('%d days, ' + pattern) % (d, h, m, s)

一些例子:

$ sec2time(10, 3)
Out: '00:00:10.000'

$ sec2time(1234567.8910, 0)
Out: '14 days, 06:56:07'

$ sec2time(1234567.8910, 4)
Out: '14 days, 06:56:07.8910'

$ sec2time([12, 345678.9], 3)
Out: ['00:00:12.000', '4 days, 00:01:18.900']

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

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

PS:我的代码不专业

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

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

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

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