Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to localize datetime in Django view code (with BST)?

Tags:

python

django

I have a datetime in "models.py":

class Foo(models.Model):
    modified = models.DateTimeField()

When I display this in a template it comes out correct i.e. according to my locale settings (I'm in British Summer Time):

{{ foo.modified }}

Settings:

LANGUAGE_CODE = 'en-gb'
TIME_ZONE = 'Europe/London'
USE_I18N = True
USE_L10N = True
USE_TZ = True

Correctly outputs what I'd expect "7 Sep 2020, 2:43 p.m." (printing "modified" in the view gives "2020-09-07 13:43:40.988953+00:00").

However when I try to copy this formatting to a string in the view I get the wrong date / time (it has not adjusted by one hour):

from django.utils.formats import localize
from app.models import Foo
foo = get_object_or_404(Foo, pk=1)
modified = localize(foo.modified, use_l10n=True)
print(modified)

Outputs "7 Sep 2020, 1:43 p.m.", which is wrong.

I tried the other answers on this thread and none outputted the adjusted datetime: Stack Overflow thread

like image 928
gornvix Avatar asked Nov 18 '25 23:11

gornvix


2 Answers

The datetime objects in your code will be in the timezone returned by your database (or database adapter). Generally UTC, as in this case, which is why the printed value is off by an hour.

These are automatically converted to the current time zone (TIME_ZONE, by default) for interactions with users (forms and templates), which is why your template view is correct.

If you want to convert the datetime object in code to the current time zone, use localtime():

from django.utils.timezone import localtime

local_modified = localtime(foo.modified)
like image 181
Kevin Christopher Henry Avatar answered Nov 20 '25 13:11

Kevin Christopher Henry


from django.utils import timezone
from django.templatetags.l10n import localize


def localize_datetime(value):
    return localize(timezone.template_localtime(value))

I've written this function for this purpose. I've tried to find out how Django handle datetime fields from the box, in Django admin it automatically convert value to the local timezone and apply formatting from formats defined in FORMAT_MODULE_PATH.

So timezone.template_localtime - convert value to local time if it settings.USE_TZ is On

And localize - apply formatting

like image 22
Слава Avatar answered Nov 20 '25 12:11

Слава



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!