How to format datetime in a Flask application?

Asked

Viewed 479 times

2

How can I make it show only dd/mm/yy and take the hours and seconds in my database or templates?

imagem de exemplo

Database:

class User(db.Model):

    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(120))
    last_name = db.Column(db.String(120))
    callsing = db.Column(db.String(10), unique=True)
    username = db.Column(db.String(120))
    ifc = db.Column(db.String(64)) 
    password = db.Column(db.String(120))
    email = db.Column(db.String(120), unique=True)  
    age = db.Column(db.String(5))
    grau = db.Column(db.String)
    about_me = db.Column(db.Text(140))
    last_seen = db.Column(db.DateTime, default=datetime.utcnow)

Template:

{% for f in range(2) %}
    <tr>
       <td><img src="../static/img/arrow-gray.png" alt="">
           <font color="#006400">IFAB {{ form[f].callsing }} </font>
       </td>
       <td>{{ form[f].first_name  }} <b>{{ form[f].last_name }}</b></td>
       <td>{{ form[f].last_seen }}</td>
    </tr>
{% endfor %}

1 answer

4


You can use the function strftime:

<td>{{ form[f].last_seen.strftime('%d/%m/%Y') }}</td>

Or create a specific filter for this.

app = ... # instância do Flask.

@app.app_template_filter('to_date')
def format_datetime(value):
    return value.strftime('%d/%m/%Y')

And then use in your template as:

<td>{{ form[f].last_seen|to_date }}</td>

It is worth remembering that in this second case it is possible to use <var>|to_date with any type of variable, so it might be interesting to do a treatment in function format_datetime to validate that the type of value received as argument datetime before trying to call the function strftime.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.