Flask-Flask-Moment发出错误:AttributeError:'str'对象没有属性'strftime'

时间:2020-07-05 22:36:20

标签: datetime flask momentjs

好,所以我想将mysql数据库中的datetime值更改为所需的格式。所以我的代码去了:

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上,我在下面的表上显示datetime值:

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似乎是唯一的方法

1 个答案:

答案 0 :(得分:0)

编辑:

您也可以尝试使用:

{{ row.created_at.strftime('%M %d, %Y') }}

或Jinja日期时间过滤器:

{{ row.created_at|datetime }}

原始答案:

似乎您需要将MySQL DateTime转换为Python datetime。在没有看到更多代码的情况下,也许可以使用类似的方法,尽管可能有一种更有效的方法:

# get results
users = cur.fetchall()

for user in users:
    user.created_at = datetime.strptime(user.created_at, '%Y-%M-%d') # you have to use the mysql format here

return render_template('users.html', title = 'User Accounts', users=users)

您正在使用strftime,而python似乎将MySQL datetime解释为字符串而不是datetime()对象,因此您必须使用strptime