[Django]-Trouble with Django unnecessarily adding 5 hours to date time.

3👍

Django stores dates in the db as UTC, so the time 20:00 is correct. If you want all your dates displayed as the GMT-0500 timezone you should set the TIME_ZONE setting and USE_TZ = True… otherwise currently Django doesn’t know what time zone you want and it’d be up to you to normalise any dates yourself eg in view code.

2👍

It’s because the datetime that is stored in the database is aware in that along date and time data, it also stores the time zone. When printing the aware datetime object, what you get is that very point in time, but in the UTC time zone (thus the 5hours delta).

>>> from datetime import datetime
>>> from django.utils.timezone import now

>>> datetime.now()
datetime.datetime(2015, 2, 2, 15, 29, 10, 202480)

>>> now()
datetime.datetime(2015, 2, 2, 21, 29, 11, 459850, tzinfo=<UTC>)

As you can see, the datetime.now() returns datetime object that is in my local time (-6 hours). The aware object is represented in the UTC timezone, which is +6 hours to my local time zone.

If you would like to make it into your local timezone use django.utils.timezone.localtime:

>>> from django.utils.timezone import now, localtime
>>> localtime(now())
datetime.datetime(2015, 2, 2, 15, 31, 25, 666377, tzinfo=<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>)

Leave a comment