我需要得到Python中任何时区的当前偏移量。目前我正在使用pytz
库,并使用以下代码获得偏移量:
import datetime
import pytz
timezone = 'America/Punta_Arenas'
datetime.datetime.now(pytz.timezone(timezone)).utcoffset().total_seconds()/60/60
//prints -3
timezone = 'America/Santiago'
datetime.datetime.now(pytz.timezone(timezone)).utcoffset().total_seconds()/60/60
//prints -4
以“美洲/圣地亚哥”为例:今年(2018年),夏令时定为5月13日,2015年全年实行夏令时,2014年定为4月27日。所以,将日期和年份分开,偏移量是'-3'或'-4'。在
我假设之前的代码不知道每个国家关于夏令时的政治决定,很可能会根据固定的DST日期或类似的东西得到补偿。既然我不知道datetime
和pytz
的螺母和螺栓,我宁愿问,这个假设是正确的吗?在
如果它不知道,我怎么能得到任何时区的实际电流偏移量?在
你的假设是不正确的。时区的政治变化通过TZ Database记录和分配。然后,这些更改将在数百个不同的库、平台和操作系统中实现,比如您提到的pytz库。在
您描述的对
America/Santiago
的更改反映在TZDB 2016c中,后者在{a3}中实现。如果您使用的是pytz 2016.3或更高版本,那么您的代码会意识到这一变化。在Pytz没问题,但您可能需要考虑改用dateutil。Version 2.5.2或更高版本具有此数据。在
相关问题 更多 >
编程相关推荐