如何将超过24小时的timedelta返回或转换为包含总小时数和分钟数(例如26:30)而不是“1天2:30”的对象?
You can use total_seconds()
to compute the number of seconds. This can then be turned into minutes or hours:
>>> datetime.timedelta(days=3).total_seconds()
259200.0
Completing the answer of Visser using timedelta.total_seconds()
:
import datetime
duration = datetime.timedelta(days = 2, hours = 4, minutes = 15)
Once we got a timedelta
object:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.