user2819573
user2819573

Reputation: 281

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.

Upvotes: 7

Views: 5741

Answers (2)

neatsoft
neatsoft

Reputation: 359

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)
...

Upvotes: 4

user2819573
user2819573

Reputation: 281

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)

Upvotes: 6

Related Questions