相关疑难解决方法(0)

格式化python timedelta对象

我对python很新.我有两个日期时间对象.我需要计算它们之间的时间值,然后以特定格式显示输出.

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
Run Code Online (Sandbox Code Playgroud)

此Turnaround_TimeObj时间增量的一个示例是"2天,22:13:45".我想格式化输出,但我无法这样做.

print Turnaround_TimeObj.strftime('%H hrs %M mins %S secs')
Run Code Online (Sandbox Code Playgroud)

不起作用.

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

totalSeconds = Turnaround_TimeObj.seconds
hours, remainder = divmod(totalSeconds, 3600)
minutes, seconds = divmod(remainder, 60)
print '%s:%s:%s' % (hours, minutes, seconds)
Run Code Online (Sandbox Code Playgroud)

但我想知道我是否可以使用像strftime这样的日期时间函数在一行中完成它.

编辑:实际上转换为秒也不起作用.如果我将时间增量"1天,3:42:54"转换为秒使用

totalSeconds = Turnaround_TimeObj.seconds
Run Code Online (Sandbox Code Playgroud)

totalSeconds值显示为13374而不是99774. ie.它忽略了"日"的价值.

python formatting datetime

33
推荐指数
7
解决办法
6万
查看次数

标签 统计

datetime ×1

formatting ×1

python ×1