将秒数转换为易读的时间格式

4
我有一个变量,其中包含秒数,我希望将其转换为详细的时间格式。目前我的代码如下:
runTime = '%s Hours:Minutes:Seconds' % time.strftime("%H:%M:%S", time.gmtime(runTime))

输出:

17:25:46 Hours:Minutes:Seconds 

我想要它格式化为这样:

,其中包含HTML。

 17 Hours 25 Minutes 46 Seconds

最终我希望能够缩短较小的值:
因此,如果值是分钟和秒,它会像这样
15 Minutes 5 Seconds

如果时间超过24小时,则显示天数。
  1 Days 15 Hours 5 Minutes 1 Seconds

https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior - vminof
2个回答

9

您应该使用优秀的dateutil,然后您的任务将变得微不足道:

>>> 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

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不是必需的格式;它更像是字符串格式化,您可以在任何地方添加单词,并使参数出现在您想要的位置。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接