Flask - Flask-Moment gives out an error: AttributeError: 'str' object has no attribute 'strftime'

Viewed 208

Ok, so i want to change a datetime value from mysql database into a desired format. so my code goes:

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)

then on my users.html, i display the datetime value on a table which goes:

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>

But when i put in the following code for the datetime:

<td>{{moment().format('LLL')}}</td> # this is working

So in short,

# 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')

What i need to know is how to format datetime value in the flask template and Flask-Moment seems to be the only way

2 Answers

EDIT:

You can also try using:

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

or the jinja datetime filter:

{{ row.created_at|datetime }}

ORIGINAL ANSWER:

It appears you need to convert from MySQL DateTime to Python datetime. Without seeing more of your code, maybe something like this would work, though there is probably a more efficient way:

# 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)

You are using strftime when it appears that python is interpreting the MySQL datetime as a string, not a datetime() object, so you have to use strptime

Momentjs couldn't parse it because it is an 'str'. Use datetime to parse the string before passing it to the momentjs object e.g

from datetime import datetime
row_created_at = datetime.strptime(row_created_at, %m %d,%Y ')

then pass it to the momentjs object like so

{{moment(row_created).format("LLL")}}

That should do the trick

Related