How do format date notation from SQL database to a HTML page using Python Flask

Viewed 465

Working on a small project that renders a database from SQL to a HTML page using Python Flask.

Trying to change the date notation from "%y-%m-%d %H:%M" to "%d-%m-%y %H:%M".

Using the below code:

   </tr>
{% for item in items %}
    <tr>
        <td>{{item[0]}}</td>
        <td>{{item[1]}}</td>
        <td>{{item[2]}}</td>
        <td>{{item[4].strftime("%d-%m-%y %H:%M")}}</td>
        <td>{{item[5].strftime("%d-%m-%y %H:%M")}}</td>
        <td>{{item[7].strftime("%d-%m-%y %H:%M")}}</td>
        <td>{{item[10].strftime("%d-%m-%y %H:%M")}}</td>
        <td>{{item[12].strftime("%d-%m-%y %H:%M")}}</td>
        <td>{{item[13]}}</td>
    </tr>

when I run the code in the localhost i get the following error.

jinja2.exceptions.UndefinedError: 'str object' has no attribute 'strftime'

Tried to define an own filter, didn't work either.

Hope all clear, Thanks.

2 Answers

You have to use datetime object not string. datetime(2013, 10, 31, 18, 23, 29, 227),

You can create a custom filter in python like

from datetime import datetime

def date(d):
     d =  datetime.strptime(d,"%y-%m-%d %H:%M")
     d.strftime("%d-%m-%y %H:%M")
     return d

app.add_template_filter(date)

In jinja use like this {{item[2] | date}}

The issue is that you have string values mixed with datetime.datetime objects in items. Before passing data to jinja, I suggest you pre-format you values:

from datetime import datetime
import re
new_items = [[i[0], i[1], i[2], i[5].strftime("%d-%m-%y %H:%M"), 
             i[6].strftime("%d-%m-%y %H:%M"), i[7].strftime("%d-%m-%y %H:%M"), 
             i[10].strftime("%d-%m-%y %H:%M"), 
             datetime(*map(int, re.findall('\d+', i[12])[:-1])).strftime("%d-%m-%y %H:%M"),
             i[13]] for i in items]

#[['12345', 'productname', '878', '16-06-21 22:40', '16-06-21 22:40', '16-06-21 22:40', '16-06-21 23:25', '16-06-21 00:25', 0]]

Now, in your template:

{% for item in items %}
    <tr>
        {%for i in item%}
           <td>{{i}}</td>
        {%endfor%}
    </tr>
{%endfor%}
Related