Convert DateTime in Django from UTC to local timezone

Convert DateTime in Django from UTC to local timezone

Posted: 10 years ago in  Python | Django |


In Django's default settings, there are TIME_ZONE and USE_TZ options that define which timezone used in admin.However in views, time fetched from database is usually UTC timezone. To convert it to local time, pytz package will get it done.


In Django's default settings, there are TIME_ZONE and USE_TZ options that define which timezone used in admin.However in views, time fetched from database is usually UTC timezone. To convert it to local time, pytz package will get it done.

First of all, install pytz

pip install pytz

Add "pytz" in INSTALLED_APP in settings.py file

Load attribute's value which is in DateTimeField, it would be in UTC timezone.

Create local timezone by using TIME_ZONE in settings file

local_timezone = pytz.timezone(settings.TIME_ZONE)

Convert to local timezone

local_datetime = local_datetime.astimezone(local_timezone)

Then manipulate it within your view before assign to context and display in template :)