Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting date times provided as strings in Django

In my Django application I get times from a webservice, provided as a string, that I use in my templates:

{{date.string}}

This provides me with a date such as:

2009-06-11 17:02:09+0000

These are obviously a bit ugly, and I'd like to present them in a nice format to my users. Django has a great built in date formatter, which would do exactly what I wanted:

{{ value|date:"D d M Y" }}

However this expects the value to be provided as a date object, and not a string. So I can't format it using this. After searching here on StackOverflow pythons strptime seems to do what I want, but being fairly new to Python I was wondering if anyone could come up with an easier way of getting date formatting using strings, without having to resort to writing a whole new custom strptime template tag?

like image 231
Tristan Brotherton Avatar asked Jun 12 '09 00:06

Tristan Brotherton


People also ask

What is the format of datetime in Django?

Python django format date dd/mm/yyyy.

What is string date/time format?

Date and time format strings A date and time format string is a string of text used to interpret data values containing date and time information. Each format string consists of a combination of formats from an available format type. Some examples of format types are day of week, month, hour, and second.

How do I format a date string in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

What is the format of datetime in Python?

format is the format – 'yyyy-mm-dd'


1 Answers

You're probably better off parsing the string received from the webservice in your view code, and then passing the datetime.date (or string) to the template for display. The spirit of Django templates is that very little coding work should be done there; they are for presentation only, and that's why they go out of their way to prevent you from writing Python code embedded in HTML.

Something like:

from datetime import datetime
from django.shortcuts import render_to_response

def my_view(request):
    ws_date_as_string = ... get the webservice date
    the_date = datetime.strptime(ws_date, "%Y-%m-%d %H:%M:%S+0000")
    return render_to_response('my_template.html', {'date':the_date})

As Matthew points out, this drops the timezone. If you wish to preserve the offset from GMT, try using the excellent third-party dateutils library, which seamlessly handles parsing dates in multiple formats, with timezones, without having to provide a time format template like strptime.

like image 175
Jarret Hardie Avatar answered Oct 20 '22 03:10

Jarret Hardie