使用pytz时区时,Python日期时间不包括DST [英] Python datetime not including DST when using pytz timezone
问题描述
如果我将UTC日期时间转换为瑞典格式,则包括夏令时(CEST)。但是,在创建以瑞典为时区的日期时间时,它将获得CET而不是CEST。为什么这样?
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>)
>>>
推荐答案
瑞典人
对象默认指定CET时区,但包含足够的信息以了解CEST何时开始和停止。
The sweden
object specifies the CET time zone by default but contains enough information to know when CEST starts and stop.
在第一个示例中,您创建了 datetime
对象并将其转换为本地时间。 sweden
对象知道您经过的UTC时间发生在夏令时,可以将其正确转换。
In the first example, you create a datetime
object and convert it to local time. The sweden
object knows that the UTC time you passed occurs during daylight savings time and can convert it appropriately.
第二个示例, datetime
构造函数始终将您的输入解释为非夏令时,并返回一个适当的对象。
In the second example, the datetime
constructor always interprets your input as not-daylight-savings-time and returns an appropriate object.
如果 datetime
将您的输入视为壁钟时间,并为您选择了适当的夏时制设置,则在一年中的时钟为退后在壁钟上,同一小时发生两次。因此, datetime
会强制您指定创建 datetime
对象时要使用的时区。
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 the datetime
object.
这篇关于使用pytz时区时,Python日期时间不包括DST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!