简体   繁体   English

夏令时感知的python中的时间戳转换

[英]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. 给定没有时区的时间戳(例如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>)

Never set tzinfo directly when creating datetimes. 创建日期时间时,请勿直接设置tzinfo Always use the localize() method of the timezone (see the note at the top of http://pytz.sourceforge.net/ ): 始终使用时区的localize()方法(请参阅http://pytz.sourceforge.net/顶部的注释):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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