我有一个以秒为单位返回信息的函数,但我需要以小时:分钟:秒为单位存储该信息。
在Python中是否有一种简单的方法将秒转换为这种格式?
我有一个以秒为单位返回信息的函数,但我需要以小时:分钟:秒为单位存储该信息。
在Python中是否有一种简单的方法将秒转换为这种格式?
当前回答
你可以用秒除以60得到分钟
import time
seconds = time.time()
minutes = seconds / 60
print(minutes)
再除以60,就得到小时数
其他回答
如果你需要约会时间。时间值,你可以用这个技巧:
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对象。
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
通过使用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 sec_to_hours(seconds):
a=str(seconds//3600)
b=str((seconds%3600)//60)
c=str((seconds%3600)%60)
d=["{} hours {} mins {} seconds".format(a, b, c)]
return d
print(sec_to_hours(10000))
# ['2 hours 46 mins 40 seconds']
print(sec_to_hours(60*60*24+105))
# ['24 hours 1 mins 45 seconds']
我很难说出一个简单的方法(至少我不记得语法),但可以使用时间。Strftime,它对格式有更多的控制:
from time import strftime
from time import gmtime
strftime("%H:%M:%S", gmtime(666))
'00:11:06'
strftime("%H:%M:%S", gmtime(60*60*24))
'00:00:00'
Gmtime用于将秒转换为strftime()所需的特殊元组格式。
注意:在23:59:59之后截断