python - 格式化 timedelta 对象

标签 python datetime formatting

我有两个 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()返回持续时间中包含的总秒数的方法。

关于python - 格式化 timedelta 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8906926/

相关文章:

C编程制作乘法表(1-12)

python - RobotFramework 无法导入 python 文件中提到的模块

python - 我应该将我的游戏放在 pygame 类中吗?

python - xl.Workbook() (pyvot) 无法打开 Excel 工作簿

javascript - 来自 JSON 的 x 轴上的 Highcharts.js DateTime 仅显示数字

php - 在 MySQL 中将日期 POST 到日期时间的正确方法

不同语言环境和时区的 Javascript 日期对象

python - 列表中的子列表

emacs - 在 LaTeX 模式 emacs 中缩进 C 代码区域

javascript - 将粘贴文本的格式保留在没有可见标记信息的文本区域中