我如何格式化大于24小时的timedelta以在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'
Run Code Online (Sandbox Code Playgroud)
我通过以下方式达到目标:
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
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?
可能定义继承的类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'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3167 次 |
| 最近记录: |