【发布时间】:2020-07-05 22:36:20
【问题描述】:
好的,所以我想将 mysql 数据库中的日期时间值更改为所需的格式。所以我的代码是:
file: app.py
from flask import Flask, render_template, flash, redirect, url_for, session, request, logging
from datetime import datetime
from flask_moment import Moment
app = Flask(__name__)
moment = Moment(app)
mysql = MySQL(cursorclass=DictCursor)
@app.route('/users')
def users():
# create cursor
cur = mysql.get_db().cursor()
# execute query
cur.execute('SELECT * FROM users')
# get results
users = cur.fetchall()
return render_template('users.html', title = 'User Accounts', users=users)
然后在我的 users.html 上,我在表格上显示日期时间值:
file: users.html
<tbody>
{% for row in users %}
<tr>
<td>{{row.id}}</td>
<td>{{row.username}}</td>
<td>{{row.fullname}}</td>
<td>{{moment(row.created_at).format('LLL')}}</td> # this causes an error
</tr>
{% endfor %}
</tbody>
但是当我为日期时间输入以下代码时:
<td>{{moment().format('LLL')}}</td> # this is working
简而言之,
# this is not working
# Causes an "AttributeError: 'str' object has no attribute 'strftime'" error
moment(row.created_at).format('LLL')
# this is working
# but i can't modify the data based on the value from mysql database
moment().format('LLL')
# by the way, this is also not working
# and it also causes the same error
row.created_at.strftime('%M %d, %Y')
我需要知道的是如何在烧瓶模板中格式化日期时间值,而 Flask-Moment 似乎是唯一的方法
【问题讨论】: