Gábor Erdős
Gábor Erdős

Reputation: 3689

DJANGO datetime wrong on template even after timezone setup

I have a DJANGO application, and I am completely lost about times.

I am located in Budapest, Hungary, my current time for these test is: 09:26

I have my timezone correctly set in settings.py

...
TIME_ZONE = 'Europe/Budapest'

USE_I18N = True

USE_L10N = True

USE_TZ = True
...

Lets say I store a datetime object in my SQLite database, the admin page will show the correct time:

enter image description here

If I query that data in a view the date is suddenly wrong.

2020-10-06 07:26:41.040463+00:00

I have read solutions that I need to activate timezone in my view, but it does not work:

tzname = pytz.timezone("Europe/Budapest")
timezone.activate(tzname)
for i in MyObject.objects.all():
    print(i.date)

returns

2020-10-06 07:26:41.040463+00:00

I usually fill my templates with Ajax JS calls, so I was not able to try template filters like this:

{{ value|timezone:"Europe/Budapest" }}

How can I change the time so that my JsonResponse sends the correct time to my templates?

Upvotes: 0

Views: 1321

Answers (2)

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 48902

Consider carefully the first sentence in the timezone documentation:

When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms.

Note that translation to local time zones only happens in templates and forms—not database queries, views, or other functions. There are many good reasons for that, one of which is that converting to a different timezone can lose information. Let's say that the datetime you got back from the database was 2:30am on October 25, 2019, Budapest time. What moment in time does that represent? You can't know, because that time occurred twice due to daylight savings time.

So the behavior you're seeing is entirely correct. If you want to convert a datetime to the local time in code use localtime():

from django.utils.timezone import localtime

local = localtime(myobject.timestamp)

Upvotes: 2

CemreY
CemreY

Reputation: 394

When you create your models, you could set the datetime to your local timezone.

from django.utils import timezone

date = models.DateTimeField(
    default=timezone.localtime(timezone.now()),
    blank=True
)

timezone.localtime(timezone.now()) will give you the time based on the TIME_ZONE given in the settings.

Moment JS: https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/

Upvotes: 0

Related Questions