convert date and time format in django -
how convert datefield of format mm/dd/yyyy format dd/mm/yyyy , timefield of format 24hrs 12hr am/pm.
this using in below circumstances
in database model getting values,so if values getting db '0' date , time format should of (dd/mm/yyyy , 12hr am/pm).
if value database field '1',the format of (mm/dd/yyyy , 24hr)
models.py
class report(models.model): user = models.foreignkey(user, null=false) manual_date = models.datefield('another date', null=true, blank=true) manual_time = models.timefield('another time', null=true, blank=true) class settings(models.model): date_format = models.charfield('date format', max_length=100) time_format = models.charfield('time format', max_length=100) how do.
thanks
i think better off handling converts @ template level using tag date. example, see pass date , time variables template. pass them unconverted , later in template wherever appear this:
{% if condition %} {{date|date:"date_format"}} {{value|time:"time_format"}} {% endif %} where "time_format" actual format want date showed , condition condition needs met.
if absolutely need within view method, can use module django.utils.dateformat this:
from django.utils.dateformat import dateformat, timeformat formatted_date = dateformat(date_variable) formatted_date.format('y-m-d') # substitute format whatever need formatted_time = timeformat(time_variable) formatted_date.format('h') # substitute format whatever need use class wherever want format date_variable , time_variable proper format string them.
also, views' code. can't return string in middle of view method do:
if request.method == 'post': if user.date_format == '0': date=datetime.datetime.strptime('%m/%d/%y').strftime('%d/%m/%y') return date that throw exception if request method post. besides, date formatting there? need format report.manual_date. don't see anywhere in code. apply said above variable want format depending on your settings , pass variable tempalte_context when return. hope helps!
Comments
Post a Comment