Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

254
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda