简体   繁体   中英

Daylight time saving aware conversion of timestamps in python

Given a timestamp without time zone (eg 2018-03-12 09:30:00 ) AND the timezone EST5EDT , the goal is to parse the data returning a datetime object that is time zone AND daylight saving aware.

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>)

Never set tzinfo directly when creating datetimes. Always use the localize() method of the timezone (see the note at the top of http://pytz.sourceforge.net/ ):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM