Last active
February 10, 2016 14:47
-
-
Save dhbradshaw/aa769272b64c5df1179c to your computer and use it in GitHub Desktop.
creating timezone-aware datetime objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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