如何在 Python 中获取 timedelta 的总小时数和分钟数

How to get total hours and minutes for timedelta in Python

如何 return 或将大于 24 小时的 timedelta 转换为包含总小时数和分钟数的对象(例如,26:30)而不是“1 天, 2:30"?

您可以使用 total_seconds() 来计算秒数。然后可以将其转换为分钟或小时:

>>> datetime.timedelta(days=3).total_seconds()
259200.0
offset_seconds = timedelta.total_seconds()

if offset_seconds < 0:
    sign = "-"
else:
    sign = "+"

# we will prepend the sign while formatting
if offset_seconds < 0:
    offset_seconds *= -1

offset_hours = offset_seconds / 3600.0
offset_minutes = (offset_hours % 1) * 60

offset = "{:02d}:{:02d}".format(int(offset_hours), int(offset_minutes))
offset = sign + offset

使用 timedelta.total_seconds() 完成 Visser 的回答:

import datetime
duration = datetime.timedelta(days = 2, hours = 4, minutes = 15)

一旦我们得到一个 timedelta 对象:

totsec = duration.total_seconds()
h = totsec//3600
m = (totsec%3600) // 60
sec =(totsec%3600)%60 #just for reference
print "%d:%d" %(h,m)

Out: 52:15