Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

253
Views
How to format datetime to string just as django does it

I have a DatetimeField that I highlight in django admin based on how old it is compared to now().

def valid_up_to_column(self):
    now = datetime.datetime.now(datetime.timezone.utc)
    delta = (now - self.valid_up_to).seconds

    if delta > 900:
        colour = '#FF0000'  # red
    else:
        return self.valid_up_to
    return format_html('<span style="background-color: {}">{}</span>', colour, self.valid_up_to)

When format_html is used the datetime is rendered as raw 2017-01-01 00:00+00:00 UTC format, but for the other case, Django's regional settings take over and format it based on locale e.g. Jan 1 2017, midnight.

How can I format the datetime to be in the same format as Django before passing it into format_html() ?

I've tried using strftime(settings.DATETIME_FORMAT) but this is the django DATETIME_FORMAT, not the same as Python's string formatting.

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Got it, there is a util format function, just pass it the DATETIME_FORMAT setting, so if its not set, L10N formatting will take it from here.

from django.utils.dateformat import format

datetime_str = format(self.valid_up_to, settings.DATETIME_FORMAT)
about 4 years ago · Santiago Trujillo Report

0

The same function could be used to format date, datetime, and time values:

from django.utils.formats import localize

formatted_value = localize(value)

Datetime related part of the localize() function:

def localize(value, use_l10n=None):
...
    elif isinstance(value, datetime.datetime):
        return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n)
    elif isinstance(value, datetime.date):
        return date_format(value, use_l10n=use_l10n)
    elif isinstance(value, datetime.time):
        return time_format(value, 'TIME_FORMAT', use_l10n=use_l10n)
...
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!