2017-10-20 142 views
0

我找到了一个简写的方法来从MongoDb中获取结果并传递给jinja模板。Flask jinja正确显示日期字段

@app.route('/home') 
def home(): 
    table = mongo.db.posts 
    result = table.find({ }).sort([("postdate", 1)]) 

    records = json.loads(json_util.dumps(result)) 
    if result.count() > 0: 
     return render_template('users/index.html', posts=records) 
    else: 
     message = 'I couldn't find any post' 
     return render_template('users/index.html', message=message) 

而且在用户/ index.html的我想显示的结果是这样的:

{% for post in posts %} 
<tr> 
    <td>{{post._id}}</td> 
    <td>{{post.title}}</td> 
    <td>{{post.author}}</td> 
    <td class="date">{{post.postdate}}</td> 
</tr> 
{% endfor %} 

一切正常,除了日期字段。有没有办法正确显示日期字段?

{'$date': 1508227970796} 
{'$date': 1508228089163} 
{'$date': 1508241780398} 

回答

1

你们看到的是这个日期的时间戳,有两种可能性来解决这个问题:在发送前阵

您CA使用这个里面你欣赏到日期转换为可读的格式到神社模板

from datetime import datetime 
datetime.fromtimestamp(the_date_you_want_to_convert) 

,或者你可以创建一个simple Jinja filter which将一个给定的时间戳转换成你的可读的日期格式。