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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27912803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:27:05  来源:igfitidea点击:

How to get total hours and minutes for timedelta in Python

pythonpython-2.7

提问by ThomasD

How do I return or turn a timedelta, which is bigger than 24 hours, into an object containing the total hours and minutes (for example, 26:30) instead of "1 day, 2:30"?

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

采纳答案by Simeon Visser

You can use total_seconds()to compute the number of seconds. This can then be turned into minutes or hours:

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

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

回答by Vineeta Khatuja

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

回答by G M

Completing the answer of Visser using timedelta.total_seconds():

使用timedelta.total_seconds()以下命令完成 Visser 的回答:

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

Once we got a timedeltaobject:

一旦我们得到一个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