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

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


当前回答

我很难说出一个简单的方法(至少我不记得语法),但可以使用时间。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之后截断

其他回答

下面是一个简单的程序,它读取当前时间并将其转换为以小时、分钟和秒为单位的一天时间

import time as tm #import package time
timenow = tm.ctime() #fetch local time in string format

timeinhrs = timenow[11:19]

t=tm.time()#time.time() gives out time in seconds since epoch.

print("Time in HH:MM:SS format is: ",timeinhrs,"\nTime since epoch is : ",t/(3600*24),"days")

输出为

Time in HH:MM:SS format is:  13:32:45 
Time since epoch is :  18793.335252338384 days

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

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

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

这是我的小把戏:

from humanfriendly import format_timespan
secondsPassed = 1302
format_timespan(secondsPassed)
# '21 minutes and 42 seconds'

欲了解更多信息,请访问: https://humanfriendly.readthedocs.io/en/latest/api.html#humanfriendly.format_timespan