jinja2 how to remove microsecond in datetime

不想你离开。 提交于 2020-05-09 06:09:31

问题


In a Jinja2 template I want to display the last login:

Last Login: {{ user.last_seen }}

last_seen is supposed to be a datetime object in sqlite.

It always gives me something like: 2014-07-27 23:09:36.467761

How do I remove the microseconds part of that when displaying on my template?


回答1:


You are using the default string formatting of a datetime object, which is essentially the same as calling datetime.isoformat(' '), a format that includes the microseconds component.

If you want a different format, then do so explicitly, using the datetime.datetime.strftime() method:

Last Login: {{ user.last_seen.strftime('%Y-%m-%d %H:%M:%S') }}

Alternatively, produce a new datetime object with the microseconds component set to 0, then interpolate that:

Last Login: {{ user.last_seen.replace(microsecond=0) }}



回答2:


Alternatively, a nice solution is flask-moment, where you can use the datetime object and specify how it is to be formatted, like so:

Last Login: {{ moment(user.last_seen).format('LLLL') }}

which would output like this:

Last Login: Tuesday, July 29 2014 11:55 AM

You could even use the fromNow() function

Last Login: {{ moment(user.last_seen).fromNow() }}
Last Login: 2 days ago


来源:https://stackoverflow.com/questions/24986602/jinja2-how-to-remove-microsecond-in-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!