如何格式化timedelta大于24小时,只显示Python中的小时数?
>>> import datetime
>>> td = datetime.timedelta(hours=36, minutes=10, seconds=10)
>>> str(td)
'1 day, 12:10:10'
# my expected result is:
'36:10:10'
我通过以下方式实现:
import datetime
td = datetime.timedelta(hours=36, minutes=10, seconds=10)
seconds = td.total_seconds()
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
str = '{}:{}:{}'.format(int(hours), int(minutes), int(seconds))
>>> print(str)
36:10:10
有更好的方法吗?
答案 0 :(得分:2)
可能正在定义继承datetime.timedelta
的类会更优雅
class mytimedelta(datetime.timedelta):
def __str__(self):
seconds = self.total_seconds()
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
str = '{}:{}:{}'.format(int(hours), int(minutes), int(seconds))
return (str)
td = mytimedelta(hours=36, minutes=10, seconds=10)
>>> str(td)
prints '36:10:10'
答案 1 :(得分:0)
from datetime import timedelta
from babel.dates import format_timedelta
delta = timedelta(days=6)
format_timedelta(delta, locale='en_US')
u'1 week'
更多信息:http://babel.pocoo.org/docs/dates/
这将根据给定的区域设置格式化您的间隔。我想它会更好,因为它将始终使用您的语言环境的官方格式。
哦,它有一个粒度参数。 (我希望我能理解你的问题......)
答案 2 :(得分:0)
td = datetime.timedelta(hours=36, minutes=10, seconds=10)
seconds = td.total_seconds()
result = '%d:%02d:%02d' % (seconds / 3600, seconds / 60 % 60, seconds % 60)