The Python Oracle

Modifying display format of DateTimes in django-tables2

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Music Box Puzzles

--

Chapters
00:00 Modifying Display Format Of Datetimes In Django-Tables2
01:02 Accepted Answer Score 9
01:22 Answer 2 Score 8
01:56 Answer 3 Score 0
02:13 Thank you

--

Full question
https://stackoverflow.com/questions/2804...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #html #django #djangotables2

#avk47



ACCEPTED ANSWER

Score 9


Problem solved.

django-table2's DateTimeColumn class seems to be looking for a SHORT_DATETIME_FORMAT rather than the DATETIME_FORMAT in my settings.py. Updated the value in my settings file and everything is in working order.




ANSWER 2

Score 8


This confused me for a while as I tried to use the Python datetime formatting options. The formatting options for Django templates apply in django-tables2, and are fully enumerated at the Django docs:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#std:templatefilter-date

From that, if you have a model with one datetime column, and you want their birthday to be formatted as Month Day Year, Hour:Minute AM/PM, then you would enter the following:

class MyTable(tables.Table):
    birthday = tables.DateTimeColumn(format ='M d Y, h:i A')

    class Meta:
        model = Person
        attrs = {'class': 'table'} 
        fields =  ['birthday']



ANSWER 3

Score 0


You can add 'format' as argument to DateTimeColumn.

https://django-tables2.readthedocs.io/en/latest/_modules/django_tables2/columns/datetimecolumn.html

class DateTimeColumn(TemplateColumn):
    """
    A column that renders `datetime` instances in the local timezone.

    Arguments:
        format (str): format string for datetime (optional).
                      Note that *format* uses Django's `date` template tag syntax.
        short (bool): if `format` is not specified, use Django's
                      ``SHORT_DATETIME_FORMAT``, else ``DATETIME_FORMAT``