Daylight time saving aware conversion of timestamps in python
给定没有时区的时间戳(例如
1 2 3 4 5 6 7 8 9 10 11 12 | 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>) |
创建日期时,切勿直接设置
1 2 3 | pytz.timezone('EST5EDT').localize( datetime(2018, 3, 12, 9, 30) ).astimezone(pytz.utc) |