[英]How can I format timedelta for display
我的腳本計算了2次的差異。 像這樣:
lasted = datetime.strptime(previous_time, FMT) - datetime.strptime(current_time, FMT)
它返回一個timedelta對象。 目前,它給了我幾秒鍾的差異。
如何格式化以便顯示?
例如,將“121”轉換為“00:02:01”?
謝謝。
你嘗試過使用str()
嗎?
>>> a = datetime.now()
>>> b = datetime.now() - a
>>> b
datetime.timedelta(0, 6, 793600)
>>> str(b)
'0:00:06.793600'
或者,您可以使用字符串格式:
>>> a = datetime.now()
>>> b = datetime.now() - a
>>> s = b.total_seconds()
>>> '{:02}:{:02}:{:02}'.format(s // 3600, s % 3600 // 60, s % 60)
'00:00:06'
您可以通過創建新的timedelta對象來截斷使用str
的秒數
>>> a = datetime.now()
>>> b = datetime.now()
>>> c = b-a
>>> str(c)
'0:00:10.327705'
>>> str(timedelta(seconds=c.seconds))
'0:00:10'
[在這里插入無恥的自我推銷免責聲明]
您可以使用https://github.com/frnhr/django_timedeltatemplatefilter
它被打包為Django的tempalte過濾器,所以這里是重要的部分,只是簡單的Python:
def format_timedelta(value, time_format="{days} days, {hours2}:{minutes2}:{seconds2}"):
if hasattr(value, 'seconds'):
seconds = value.seconds + value.days * 24 * 3600
else:
seconds = int(value)
seconds_total = seconds
minutes = int(floor(seconds / 60))
minutes_total = minutes
seconds -= minutes * 60
hours = int(floor(minutes / 60))
hours_total = hours
minutes -= hours * 60
days = int(floor(hours / 24))
days_total = days
hours -= days * 24
years = int(floor(days / 365))
years_total = years
days -= years * 365
return time_format.format(**{
'seconds': seconds,
'seconds2': str(seconds).zfill(2),
'minutes': minutes,
'minutes2': str(minutes).zfill(2),
'hours': hours,
'hours2': str(hours).zfill(2),
'days': days,
'years': years,
'seconds_total': seconds_total,
'minutes_total': minutes_total,
'hours_total': hours_total,
'days_total': days_total,
'years_total': years_total,
})
沒有比這更簡單:)盡管如此,請查看自述文件以獲取一些示例。
對於你的例子:
>>> format_timedelta(lasted, '{hours_total}:{minutes2}:{seconds2}')
0:02:01
希望這可以解決你的問題,
import datetime
start = datetime.datetime(2012,11,16,11,02,59)
end = datetime.datetime(2012,11,20,16,22,53)
delta = end-start
print ':'.join(str(delta).split(':')[:3])
In [29]: import datetime
In [30]: start = datetime.datetime(2012,11,16,11,02,59)
In [31]: end = datetime.datetime(2012,11,20,16,22,53)
In [32]: delta = end-start
In [33]: print ':'.join(str(delta).split(':')[:3])
4 days, 5:19:54
擴展@ blender的答案。 如果您對毫秒分辨率感興趣
a = datetime.now()
b = datetime.now() - a
s = b.seconds
ms = int(b.microseconds / 1000)
'{:02}:{:02}:{:02}.{:03}'.format(s // 3600, s % 3600 // 60, s % 60, ms)
該小數第二位有時是時間delta所不需要的。 使用拆分和丟棄快速截斷該小數位:
a = datetime.now()
b = datetime.now() - a
然后
str(b).split('.')[0]
(假設應用程序中的一小部分與您無關)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.