75
The django.utils.formats
module is what you’re looking for. The only reference I could find in the docs was in the Django 1.2 release notes.
Remember that the localisation will only work if the USE_L10N
setting is True
. You can use the date_format as follows.
from datetime import datetime
from django.utils import formats
date_joined = datetime.now()
formatted_datetime = formats.date_format(date_joined, "SHORT_DATETIME_FORMAT")
27
You might want to try using django.utils.dateformat.DateFormat
>>> from datetime import datetime
>>> dt = datetime.now()
>>> from django.utils.dateformat import DateFormat
>>> from django.utils.formats import get_format
>>> df = DateFormat(dt)
>>> df.format(get_format('DATE_FORMAT'))
u'April 23, 2013'
>>> df.format('Y-m-d')
u'2013-04-23'
More information using Python:
import django
help(django.utils.dateformat)
- [Django]-Django, creating a custom 500/404 error page
- [Django]-How can I enable CORS on Django REST Framework
- [Django]-How to use refresh token to obtain new access token on django-oauth-toolkit?
13
To use the Django date filter in a view use defaultfilters
, e.g.:
from django.template import defaultfilters
formatted_date = defaultfilters.date(usr.date_joined, "SHORT_DATETIME_FORMAT")
- [Django]-Django-admin: Add extra row with totals
- [Django]-Best way to make Django's login_required the default
- [Django]-Django templates: forloop.first and forloop.last
5
Use localize
shortcut.
>>> from django.utils.formats import localize
>>> from datetime import datetime
>>>
>>> print(datetime.now())
2016-12-18 19:30:35.786818
>>> print(localize(datetime.now()))
18 декабря 2016 г. 19:30
- [Django]-Are there any plans to officially support Django with IIS?
- [Django]-Django migrate –fake and –fake-initial explained
- [Django]-Django: add image in an ImageField from image url
- [Django]-Django: TypeError: 'tuple' object is not callable
- [Django]-How to reverse the URL of a ViewSet's custom action in django restframework
- [Django]-How to start doing TDD in a django project?
0
As of today what worked for me was setting USE_L10N to True.
Then import some utils :
from django.utils import (dateformat, formats)
Which can be used as such :
dateformat.format(my_date_object, formats.get_format('DATE_FORMAT'))
Note thate my_date_object
should be a datetime object.
And there is a list of available formats :
- DECIMAL_SEPARATOR
- THOUSAND_SEPARATOR
- NUMBER_GROUPING
- FIRST_DAY_OF_WEEK
- MONTH_DAY_FORMAT
- TIME_FORMAT
- DATE_FORMAT
- DATETIME_FORMAT
- SHORT_DATE_FORMAT
- SHORT_DATETIME_FORMAT
- YEAR_MONTH_FORMAT
- DATE_INPUT_FORMATS
- TIME_INPUT_FORMATS
- DATETIME_INPUT_FORMATS
The name is pretty self explanatory…
see : https://github.com/django/django/blob/main/django/utils/formats.py
- [Django]-Tailwindcss: fixed/sticky footer on the bottom
- [Django]-Adding a APIView to Django REST Framework Browsable API
- [Django]-Django: How can I protect against concurrent modification of database entries