简体   繁体   中英

Convert string to datetime in django?

我想在django模板中以12小时格式显示时间,因为iam将时间数据存储在charecter的eg('18:30:00')字段中,如何将此字符串时间数据转换为django / python中的日期?

If you absolutely must do this, use time.strptime . It would be a better idea not to store structured data in a string if you can avoid it, though.

Within Django's templates you can use the date Template Filter:

{{ value|date:"h:i:s a" }}   # '18:30:00' would appear as  6:30:00 p.m.
{{ value|date:"g:i:s a" }}   # '18:30:00' would appear as 06:30:00 p.m.

value would be the string variable you pass in the Context to the Template when you render it. The string appearing after date: formats the time.

You can find more here: http://docs.djangoproject.com/en/1.3/ref/templates/builtins/#date


Hank Gay's answer is more correct than mine; you should avoid keeping structured data in a string if at all possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM