timedelta
手动格式化:
def custom_format(td):
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return '{:d}:{:02d}'.format(hours, minutes)
演示:
>>> from datetime import timedelta
>>> def custom_format(td):
... minutes, seconds = divmod(td.seconds, 60)
... hours, minutes = divmod(minutes, 60)
... return '{:d}:{:02d}'.format(hours, minutes)
...
>>> custom_format(timedelta(hours=9, minutes=46, seconds=4, microseconds=352515))
'9:46'
此方法确实忽略了该.days
属性。如果您的时间增量超过 24 小时,请使用:
def custom_format(td):
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
formatted = '{:d}:{:02d}'.format(hours, minutes)
if td.days:
formatted = '{} day{} {}'.format(
td.days, 's' if td.days > 1 else '', formatted)
return formatted
演示:
>>> custom_format(timedelta(days=42, hours=9, minutes=46, seconds=4, microseconds=352515))
'42 days 9:46'
>>> custom_format(timedelta(days=1, hours=9, minutes=46, seconds=4, microseconds=352515))
'1 day 9:46'
>>> custom_format(timedelta(hours=9, minutes=46, seconds=4, microseconds=352515))
'9:46'