【发布时间】:2015-12-07 13:39:57
【问题描述】:
如何格式化大于 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'
我做到了:
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
有没有更好的办法?
【问题讨论】:
-
我觉得这已经够干净了,你为什么不用时间戳
-
@Sinux 因为我对时间对象做了一些计算 (
+, -)。 -
如果我想从以下命令中删除日期: td = datetime.timedelta(hours= h,hours = m,hours = s) 以获得以下结果 12:10:10而不是:“1 天,12:10:10”有人会怎么做?!