![](/img/trans.png)
[英]How do I convert datetime.timedelta to minutes, hours in Python?
[英]How to get total hours and minutes for timedelta in Python
如何将超过24小时的timedelta返回或转换为包含总小时数和分钟数(例如26:30)而不是“1天2:30”的对象?
您可以使用total_seconds()
来计算秒数。 然后可以将其转换为几分钟或几小时:
>>> datetime.timedelta(days=3).total_seconds()
259200.0
使用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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.