Kinsa | Pixels + Logic Blog

Use Django's settings.TIME_ZONE to create a time zone aware datetime object

Make a datetime object time zone aware by replacing tzinfo with a pytz.timezone:

import pytz

from datetime import datetime

from django.conf import settings


datetime(2020, 4, 23).replace(tzinfo=pytz.timezone(settings.TIME_ZONE))

A similar trick can be used to get the current time in a time zone:

import pytz

from datetime import datetime

from django.conf import settings


datetime.now(pytz.timezone(settings.TIME_ZONE))

Or, get the datetime in another time zone, such as UTC. Here, simply passing pytz.utc rather than querying pytz by a key string as when doing so by passing settings.TIME_ZONE:

import pytz

from datetime import datetime


datetime.now(pytz.utc)

Feedback?

Email us at hello@kinsa.us.