Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timezone not working properly in Django

I want to change timezone in Django, so I read documentation how to do it nad here's what I've got:

#settings.py
TIME_ZONE = 'Europe/Ljubljana'

#models.py   #date_time gets filled with "auto_now=True")
date_time = models.DateTimeField(auto_now=True)

UTC DST offset for given location (Europe/Ljubljana) is +2, while in my db I see timestamp of UTC. So what am I missing?

Or is this working as intended so it gets processed for each request separately (useful for people in different timezones)? But if this is the case, what's the use of setting TIME_ZONE = 'Europe/Ljubljana'?

like image 758
user3053452 Avatar asked Jul 25 '16 11:07

user3053452


1 Answers

From the 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.

so the datetime in your DB will always be stored in UTC, but will be displayed using the correct TZ in templates and forms.

To get the date in correct TZ elsewhere, use astimezone():

>>> from myapp.models import Details
>>> import pytz
>>> d = Details.objects.get(pk=1)
>>> d.added
datetime.datetime(2016, 5, 28, 18, 59, 55, 841193, tzinfo=<UTC>)
>>> localdate = d.added.astimezone(pytz.timezone('Europe/Ljubljana'))
>>> localdate
datetime.datetime(2016, 5, 28, 20, 59, 55, 841193, tzinfo=<DstTzInfo 'Europe/Ljubljana' CEST+2:00:00 DST>)
like image 143
rafalmp Avatar answered Oct 26 '22 13:10

rafalmp