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

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


当前回答

如果你需要约会时间。时间值,你可以用这个技巧:

my_time = (datetime(1970,1,1) + timedelta(seconds=my_seconds)).time()

您不能将timedelta添加到time,但可以将它添加到datetime。

UPD:这是同一技巧的另一种变体:

my_time = (datetime.fromordinal(1) + timedelta(seconds=my_seconds)).time()

你可以用任何大于0的数字来代替1。这里我们使用的事实是datetime.fromordinal将总是返回时间分量为零的datetime对象。

其他回答

小时(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,就得到小时数

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

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

使用日期时间:

使用':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

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

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