使用 pytz 时区时 Python 日期时间不包括 DST
如果我将 UTC 日期时间转换为瑞典格式,则包含夏令时 (CEST)。但是,在创建以瑞典作为时区的日期时间时,它会得到 CET 而不是 CEST。这是为什么呢?
>>> # Modified for readability
>>> import pytz
>>> import datetime
>>> sweden = pytz.timezone('Europe/Stockholm')
>>>
>>> datetime.datetime(2010, 4, 20, 16, 20, tzinfo=pytz.utc).astimezone(sweden)
datetime(2010, 4, 20, 18, 20, tzinfo=<... 'Europe/Stockholm' CEST+2:00:00 DST>)
>>>
>>> datetime.datetime(2010, 4, 20, 18, 20, tzinfo=sweden)
datetime(2010, 4, 20, 18, 20, tzinfo=<... 'Europe/Stockholm' CET+1:00:00 STD>)
>>>
If I convert a UTC datetime to swedish format, summertime is included (CEST). However, while creating a datetime with sweden as the timezone, it gets CET instead of CEST. Why is this?
>>> # Modified for readability
>>> import pytz
>>> import datetime
>>> sweden = pytz.timezone('Europe/Stockholm')
>>>
>>> datetime.datetime(2010, 4, 20, 16, 20, tzinfo=pytz.utc).astimezone(sweden)
datetime(2010, 4, 20, 18, 20, tzinfo=<... 'Europe/Stockholm' CEST+2:00:00 DST>)
>>>
>>> datetime.datetime(2010, 4, 20, 18, 20, tzinfo=sweden)
datetime(2010, 4, 20, 18, 20, tzinfo=<... 'Europe/Stockholm' CET+1:00:00 STD>)
>>>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
sweden
对象默认指定 CET 时区,但包含足够的信息来了解 CEST 何时开始和停止。在第一个示例中,您创建一个
datetime
对象并将其转换为本地时间。sweden
对象知道您传递的 UTC 时间发生在夏令时期间,并且可以对其进行适当的转换。在第二个示例中,
datetime
构造函数始终将您的输入解释为非夏令时并返回适当的对象。如果
datetime
将您的输入视为挂钟时间并为您选择适当的夏令时设置,那么在一年中的某个时间调回时钟时,就会出现歧义。在挂钟上,同一时间会出现两次。因此,datetime
会强制您在创建datetime
对象时指定所使用的时区。The
sweden
object specifies the CET time zone by default but contains enough information to know when CEST starts and stop.In the first example, you create a
datetime
object and convert it to local time. Thesweden
object knows that the UTC time you passed occurs during daylight savings time and can convert it appropriately.In the second example, the
datetime
constructor always interprets your input as not-daylight-savings-time and returns an appropriate object.If
datetime
treated your input as wall-clock time and chose the appropriate daylight-savings setting for you, there would be an ambiguity during the time of year when clocks are set back. On a wall-clock the same hour occurs twice. Hence,datetime
forces you to specify which timezone you're using when you create thedatetime
object.时区缩写并不唯一。例如,“IST”可以指“爱尔兰标准时间”、“伊朗标准时间”、“印度标准时间”或“以色列标准时间”。您不应该依赖于解析它,而应该使用 zoneinfo 时区。
Timezone abbreviations are not unique. For example "IST" could refer to "Irish Standard Time", "Iranian Standard Time", "Indian Standard Time" or "Isreali Standard Time". You shouldn't rely on parsing that, and instead should use zoneinfo timezones.