Convert string to datetime in django?

匿名 (未验证) 提交于 2019-12-03 02:43:01

问题:

i want to display time in 12 hour format in django templates as iam storing time data in a charecter eg('18:30:00') field how to convert this string time data to date in django/python?

回答1:

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.



回答2:

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.



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