Skip to content

Instantly share code, notes, and snippets.

@zed
Created August 18, 2014 21:22
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 zed/f6d6e0d10cf0ead414d6 to your computer and use it in GitHub Desktop.
Save zed/f6d6e0d10cf0ead414d6 to your computer and use it in GitHub Desktop.
Demonstrate why pytz.timezone.normalize() may be useful after datetime.replace() in Python
"""Demonstrate why tz.normalize() may be useful after dt.replace()."""
from datetime import datetime
import pytz
# see Localized times and date arithmetic section in pytz docs
# http://pytz.sourceforge.net/#localized-times-and-date-arithmetic
eastern = pytz.timezone('US/Eastern')
dt = eastern.localize(datetime(2002, 10, 27, 7, 0, 0), is_dst=None)
unnormalized_dt = dt.replace(hour=0, minute=0, second=0)
print(unnormalized_dt.utcoffset())
# -> -1 day, 19:00:00
print(eastern.normalize(unnormalized_dt).utcoffset())
# -> -1 day, 20:00:00 #NOTE: different!!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment