我有一个包含秒的变量,我想转换为详细的时间格式。我现在就是这样。
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
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
您应该逐步执行此操作,首先确定天/小时,然后添加分钟/秒。
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
不是必需的格式;它更像是字符串格式,您可以在任意位置添加单词,并使参数出现在您想要的位置。
这就是我所拥有的。它是通用的,报告的持续时间从微秒到数年不等,仅根据最重要的信息组成结果。您可以使用
parts_count
来减少或增加返回的时间部分数量。
def readable_duration(seconds: float, parts_count: int = 2) -> str:
"""Returns readable time span out of number of seconds. No rounding."""
parts_with_units = [
(60 * 60 * 24 * 365, "y"),
(60 * 60 * 24 * 7, "w"),
(60 * 60 * 24, "d"),
(60 * 60, "h"),
(60, "m"),
(1, "s"),
(1e-3, "ms"),
(1e-6, "us"),
]
info = ""
remaining = abs(seconds)
for time_part, unit in parts_with_units:
partial_amount = int(remaining // time_part)
if partial_amount:
optional_space = " " if info else ""
info += f"{optional_space}{partial_amount}{unit}"
remaining %= time_part
parts_count -= 1
if not parts_count:
break
if not info and seconds != 0:
return "~0s"
return info or "0s"
def test_readable_duration():
assert readable_duration(0) == "0s"
assert readable_duration(0.0) == "0s"
assert readable_duration(0.00001234567) == "12us"
assert readable_duration(1.2345) == "1s 234ms"
assert readable_duration(12) == "12s"
assert readable_duration(12.345) == "12s 345ms"
assert readable_duration(123) == "2m 3s"
assert readable_duration(1234) == "20m 34s"
assert readable_duration(12345) == "3h 25m"
assert readable_duration(123456) == "1d 10h"
assert readable_duration(1234567) == "2w 6h"
assert readable_duration(12345678) == "20w 2d"
assert readable_duration(123456789) == "3y 47w"
assert readable_duration(1e-10) == "~0s"