python - 格式化 timedelta 对象

我有两个 datetime 对象。我需要计算它们之间的 timedelta,然后以特定格式显示输出。

Alpha_TimeObj = datetime.datetime(int(AlphaTime.strftime('%Y')), int(AlphaTime.strftime('%m')), int(AlphaTime.strftime('%d')), int(AlphaTime.strftime('%H')), int(AlphaTime.strftime('%M')), int(AlphaTime.strftime('%S')))
Beta_TimeObj = datetime.datetime(int(BetaTime.strftime('%Y')), int(BetaTime.strftime('%m')), int(BetaTime.strftime('%d')), int(BetaTime.strftime('%H')), int(BetaTime.strftime('%M')), int(BetaTime.strftime('%S')))
Turnaround_TimeObj = Beta_TimeObj  - Alpha_TimeObj

Turnaround_TimeObj 时间增量的一个示例是“2 天,22:13:45”。我想格式化输出,但我做不到。

print Turnaround_TimeObj.strftime('%H hrs %M mins %S secs')

没用。

我知道这样做的一种方法是将其转换为秒,然后进行 divmoding 以获得所需的格式。

如:

totalSeconds = Turnaround_TimeObj.seconds
hours, remainder = divmod(totalSeconds, 3600)
minutes, seconds = divmod(remainder, 60)
print '%s:%s:%s' % (hours, minutes, seconds)

但我想知道是否可以使用任何日期时间函数(如 strftime)在一行中完成。

实际上转换为秒也不起作用。如果我使用以下方法将时间增量“1 天,3:42:54”转换为秒:

totalSeconds = Turnaround_TimeObj.seconds

totalSeconds 值显示为 13374 而不是 99774。即它忽略了“day”值。

最佳答案

But I was wondering if I can do it in a single line using any date time function like strftime.

据我所知,timedelta 没有内置方法可以做到这一点。如果你经常这样做,你可以创建自己的函数,例如

def strfdelta(tdelta, fmt):
    d = {"days": tdelta.days}
    d["hours"], rem = divmod(tdelta.seconds, 3600)
    d["minutes"], d["seconds"] = divmod(rem, 60)
    return fmt.format(**d)

用法:

>>> print strfdelta(delta_obj, "{days} days {hours}:{minutes}:{seconds}")
1 days 20:18:12
>>> print strfdelta(delta_obj, "{hours} hours and {minutes} to go")
20 hours and 18 to go

如果您想使用更接近 strftime 使用的字符串格式,我们可以使用 string.Template :

from string import Template

class DeltaTemplate(Template):
    delimiter = "%"

def strfdelta(tdelta, fmt):
    d = {"D": tdelta.days}
    d["H"], rem = divmod(tdelta.seconds, 3600)
    d["M"], d["S"] = divmod(rem, 60)
    t = DeltaTemplate(fmt)
    return t.substitute(**d)

用法:

>>> print strfdelta(delta_obj, "%D days %H:%M:%S")
1 days 20:18:12
>>> print strfdelta(delta_obj, "%H hours and %M to go")
20 hours and 18 to go

The totalSeconds value is shown as 13374 instead of 99774. I.e. it's ignoring the "day" value.

请注意,在上面的示例中,您可以使用 timedelta.days 来获取“天”值。

或者,从 Python 2.7 开始,timedelta 具有 total_seconds()返回持续时间中包含的总秒数的方法。

https://stackoverflow.com/questions/8906926/

相关文章:

Java - 将双值格式化为美元金额

asp.net - 如何在 ASP.NET RadioButtonList 中的项目之间添加空格

python - 以元组为参数的新样式格式

objective-c - 将 ISO 8601 转换为 NSDate

java - 如何使用 Java 的 DecimalFormat 进行 "smart"货币格式?

java - 使用 Java 将电话号码转换为国际格式 (E.164) 的最佳方法是什么?

formatting - excel中的数字格式: Showing % value without

xml - 如何在 sublime 3 中安装 sublime text indent xml

c# - 我如何在 c# 中格式化 07/03/2012 到 2012 年 3 月 7 日

javascript - 如何设置 VSCode 以将花括号放在新行上?