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

时间:2015-01-12 23:53:49

标签: python python-2.7

如何将超过24小时的timedelta返回或转换为包含总小时数和分钟数(例如26:30)的对象,而不是" 1天,2:30&#34 ;

3 个答案:

答案 0 :(得分:24)

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

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

答案 1 :(得分:8)

使用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

答案 2 :(得分: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