user2161650
user2161650

Reputation:

convert date and time format in django

How to convert datefield of format mm/dd/yyyy to format dd/mm/yyyy and timefield of format 24hrs to 12hr AM/PM.

This is i am using in below circumstances

In database from a model i am getting values,so if the values getting from db is '0' the date and time format should be of (dd/mm/yyyy and 12hr AM/PM).

If the value from database field is '1',the format is of (mm/dd/yyyy and 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 to do.

Thanks

Upvotes: 1

Views: 4063

Answers (1)

Paulo Bu
Paulo Bu

Reputation: 29804

I think you are better off handling this converts at the template level using the tag date. For example, I see you pass the date and time variables to the template. Just pass them unconverted and later in the template wherever they appear do this:

{% if condition %}
    {{date|date:"DATE_FORMAT"}}
    {{value|time:"TIME_FORMAT"}}
{% endif %}

where "TIME_FORMAT" is the actual format that you want the date to be showed and condition is the condition that needs to be met.

If you absolutely need to do this within the view method, then you can use the module django.utils.dateformat like this:

from django.utils.dateformat import DateFormat, TimeFormat
formatted_date = DateFormat(date_variable)
formatted_date.format('Y-m-d') # substitute this format for whatever you need
formatted_time = TimeFormat(time_variable)
formatted_date.format('h') # substitute this format for whatever you need

Use that class wherever you want to format your date_variable and time_variable with the proper format string for them.

Also, about your views' code. You can't just return a string in the middle of a view method like you do:

if request.method == 'POST':
    if user.date_format == '0':
        date=datetime.datetime.strptime('%m/%d/%Y').strftime('%d/%m/%Y')
        return date

That will throw an exception if the request method is POST. Besides, what date are you formatting there? You need to format your report.manual_date. I don't see that anywhere in the code. Apply what I said above to the variable you want to format depending on your settings and pass that variable to the tempalte_context when you return. I hope it helps!

Upvotes: 2

Related Questions