![](/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.