Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formating Django Datetime objects outside template

Tags:

python

django

I love the date tag that comes with Django.

Exceptionally, I'd like to format a DateTime object in my view (because I need to send a formated date string to an API, and not to display it in a Django template).

Do you know if there is a way to use this Django "system" outside templates?

In the mean time, I tried to use the strftime Python method but found out some con's:

  • It does not use the same format chars as Django, which makes my code deals with 2 different ways to handle date formatting.
  • By default, it doesn't care about the Django locales and writes English dates.

Thanks :)

like image 826
David D. Avatar asked Oct 26 '25 11:10

David D.


1 Answers

The template tag is built on the Django formats utility libraries. See django.utils.formats.date_format for a named date format or django.utils.formats.dateformat.format for arbitrary ones. For example:

from datetime import datetime

# Date format string
from django.utils.formats import dateformat
formatted_date = dateformat.format(datetime.now(), "r")

# Named format
from django.utils.formats import date_format
formatted_date = date_format(datetime.now(), "SHORT_DATE_FORMAT")
like image 179
Hamish Avatar answered Oct 29 '25 00:10

Hamish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!