我有一个以秒为单位返回信息的函数,但我需要以小时:分钟:秒为单位存储该信息。
在Python中是否有一种简单的方法将秒转换为这种格式?
我有一个以秒为单位返回信息的函数,但我需要以小时:分钟:秒为单位存储该信息。
在Python中是否有一种简单的方法将秒转换为这种格式?
当前回答
在我的例子中,我想要实现格式 “HH: MM: SS.fff”。 我是这样解决的:
timestamp = 28.97000002861023
str(datetime.fromtimestamp(timestamp)+timedelta(hours=-1)).split(' ')[1][:12]
'00:00:28.970'
其他回答
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
这是我的小把戏:
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
下面这套对我很有用。
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']
你可以用秒除以60得到分钟
import time
seconds = time.time()
minutes = seconds / 60
print(minutes)
再除以60,就得到小时数
在我的例子中,我想要实现格式 “HH: MM: SS.fff”。 我是这样解决的:
timestamp = 28.97000002861023
str(datetime.fromtimestamp(timestamp)+timedelta(hours=-1)).split(' ')[1][:12]
'00:00:28.970'