5

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'?

1 Answer 1

5

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>)
Sign up to request clarification or add additional context in comments.

6 Comments

Hmm, this appears to be a problem for me since, I want to change this timestamp into epoch - needed for highcharts. Any suggestions for workaround?
By setting the TIME_ZONE option in your DATABASE settings you can force Django to store datetimes in local time - but that will force you to use a database that doesn't support time zones (SQLite, MySQL, Oracle).
That's cool, currently I'm using MySQL, so I'll look into it!
Ah, forgot the easier and interoperable way - you can use the astimezone function to convert between TZs on the fly: date_time.astimezone(pytz.timezone('Europe/Ljubljana')), my bad.
So I should use this snippet of code in my script when calling from db?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.