python 中的夏令时时间戳转换

Daylight time saving aware conversion of timestamps in python

给定一个没有时区的时间戳(例如 2018-03-12 09:30:00)和时区 EST5EDT,目标是解析返回时区和夏令时感知的日期时间对象的数据。

from datetime import datetime
import pytz

datetime(2018, 3, 8, 9, 30, tzinfo=pytz.timezone('EST5EDT')).astimezone(pytz.utc)
# returns:
# datetime.datetime(2018, 3, 8, 14, 30, tzinfo=<UTC>)

datetime(2018, 3, 12, 9, 30, tzinfo=pytz.timezone('EST5EDT')).astimezone(pytz.utc)
# returns:
# datetime.datetime(2018, 3, 12, 14, 30, tzinfo=<UTC>)
# BUT should return (second Sunday of march the daylight saving changes by 1 hour):
# datetime.datetime(2018, 3, 12, 13, 30, tzinfo=<UTC>)

切勿在创建日期时间时直接设置 tzinfo。始终使用时区的 localize() 方法(请参阅 http://pytz.sourceforge.net/ 顶部的注释):

pytz.timezone('EST5EDT').localize(
    datetime(2018, 3, 12, 9, 30)
).astimezone(pytz.utc)