bslatkin / effectivepython

Effective Python: Second Edition — Source Code and Errata for the Book
https://effectivepython.com
2.24k stars 718 forks source link

Item 45: Use datetime Instead of time for Local Clocks #43

Closed cfchou closed 8 years ago

cfchou commented 8 years ago

p.165 there's a snippet demonstrating pytz:

arrival_nyc = '2014-05-01 23:33:24'
nyc_dt_naive = datetime.strptime(arrival_nyc, time_format)
eastern = pytz.timezone('US/Eastern')
nyc_dt = eastern.localize(nyc_dt_naive)
utc_dt = pytz.utc.normalize(nyc_dt.astimezone(pytz.utc))
print(utc_dt)

I don't quite understand this line utc_dt = pytz.utc.normalize(nyc_dt.astimezone(pytz.utc)). Which seems to me tries to convert to utc datetime twice.

I tried utc_dt = pytz.utc.normalize(nyc_dt) and I feel that's sufficient unless I miss something.

bslatkin commented 8 years ago

See the pytz guide, specifically in this section it says:

You can take shortcuts when dealing with the UTC side of timezone conversions. normalize() and localize() are not really necessary when there are no daylight saving time transitions to deal with.

So in this example, if the other timezone was not UTC, then you'd need both astimezone (to convert timezones) and normalize (to make sure you account for daylight savings time).