我有变量,有秒,我想转换为详细的时间格式。我现在喜欢这个。
runTime = '%s Hours:Minutes:Seconds' % time.strftime("%H:%M:%S", time.gmtime(runTime))
输出:
17:25:46 Hours:Minutes:Seconds
我希望将其格式化为:
17 Hours 25 Minutes 46 Seconds
最终,我希望能够缩短较小的值:
因此,如果值为分钟和秒,则需要
15 Minutes 5 Seconds
如果有超过24小时,那么几天
1 Days 15 Hours 5 Minutes 1 Seconds
答案 0 :(得分:9)
你应该使用优秀的dateutil
package然后你的任务就变得微不足道了:
>>> from dateutil.relativedelta import relativedelta as rd
>>> fmt = '{0.days} days {0.hours} hours {0.minutes} minutes {0.seconds} seconds'
>>> print(fmt.format(rd(seconds=62745)))
0 days 17 hours 25 minutes 45 seconds
一些高级示例,仅显示非零值字段的值:
>>> intervals = ['days','hours','minutes','seconds']
>>> x = rd(seconds=12345)
>>> print(' '.join('{} {}'.format(getattr(x,k),k) for k in intervals if getattr(x,k)))
3 hours 25 minutes 45 seconds
>>> x = rd(seconds=1234432)
>>> print(' '.join('{} {}'.format(getattr(x,k),k) for k in intervals if getattr(x,k)))
14 days 6 hours 53 minutes 52 seconds
答案 1 :(得分:0)
您应该逐步执行此操作,首先确定日期/小时,然后添加分钟/秒。
import time
current_time = time.gmtime() # Or whatever time.
hours = int(time.strftime("%H", current_time))
days = hours / 24
hours = hours % 24
time_string = ""
if days > 0:
time_string += "%d Days " % days
if hours > 0:
time_string += "%d Hours " % hours
time_string += time.strftime("%M Minutes %S Seconds", current_time)
您可以将额外的字词直接放入time.strftime
的第一个参数中。 %H:%M:%S
不是必需的格式;它更像是字符串格式,你可以在任何地方添加单词并让参数出现在你想要的地方。