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
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With