2015-04-16 32 views
0

您好我有Django的模板標籤,Django的模板標籤過濾器顯示「浮點數是必需的」錯誤

@register.filter("timestamp") 
def timestamp(value): 
    try: 
     return datetime.fromtimestamp(value).strftime('%Y-%m-%d %H:%M:%S') 
    except AttributeError: 
     return 'error' 
    except KeyError: 
     return 'error' 

和我通過這個過濾器到我的網頁如下,

<td>{{ table.last_updated|timestamp}}</td> 

但返回一個錯誤,「需要一個浮點數」。請幫助我。由於

+0

btw,my table.last_updated是一個unixtimestamp –

回答

0

如果使用MySQLdb模塊來從你database.It數據將轉換您unixtimestamp db column到Python類型datetime.datetime。而datetime.fromtimestamp功能使用float對象作爲輸入PARAMS。

因此,您應該在時間戳功能中添加條件。如果value的類型爲datetime.datetime,請將該值轉換爲float

import time 
import datetime 
print time.mktime(datetime.datetime.now().utctimetuple()) 
0

感謝amow。這是富有成效的。我嘗試了下面的方法,它工作。

@register.filter("timestamp") 
def timestamp(value): 
    if value is not None: 
     return datetime.fromtimestamp(value).strftime('%Y-%m-%d %H:%M:%S') 
    else: 
     return 'None'