Skip to content

Instantly share code, notes, and snippets.

@dhbradshaw
Last active February 10, 2016 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhbradshaw/aa769272b64c5df1179c to your computer and use it in GitHub Desktop.
Save dhbradshaw/aa769272b64c5df1179c to your computer and use it in GitHub Desktop.
creating timezone-aware datetime objects
from django.utils import timezone
import pytz
pytz_tz = pytz.timezone('America/Chicago')
# wrong -- The direct approach leads to somewhat random time offsets between timezones.
adt = timezone.datetime(year=2016, month=1, day=6, tzinfo=pytz_tz)
# correct: Localize a naive datetime.
ndt = timezone.datetime(year=2016, month=1, day=6)
adt = pytz_tz.localize(ndt)
# Bonus: once your datetime is aware, you can easily change timezones.
denver_tz = pytz.timezone('America/Denver')
denver_adt = adt.astimezone(denver_tz)
# Summary: You want an aware datetime in your timezone of choice, pytz_tz.
# If you have a naive datetime, use localize, a method on pytz timezone obects:
adt = pytz_tz.localize(ndt)
# If you have an aware datetime, use astimezone, a method on aware datetime obects.
adt = adt.astimezone(pytz_tz)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment