Search code examples
pythondjangotemplatetag

Django template tag filter is showing "a float is required" error


Hi I have django template tag,

@register.filter("timestamp")
def timestamp(value):
    try:
        return datetime.fromtimestamp(value).strftime('%Y-%m-%d %H:%M:%S')
    except AttributeError:
        return 'error'
    except KeyError:
        return 'error'

and am passing this filter to my webpage as follows,

<td>{{ table.last_updated|timestamp}}</td>

But it returns an error, "a float is required". Please help me on this. Thanks


Solution

  • If you are using MySQLdb module to get data from your database.It will convert your unixtimestamp db column to python type datetime.datetime.And datetime.fromtimestamp function use a float object as input params.

    So you should add a condition in your timestamp function.If the type of value is datetime.datetime,convert the value to float.

    import time
    import datetime
    print time.mktime(datetime.datetime.now().utctimetuple())