如何在Python中获取任意时区的当前偏移量

2024-09-27 00:11:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要得到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日期或类似的东西得到补偿。既然我不知道datetimepytz的螺母和螺栓,我宁愿问,这个假设是正确的吗?在

如果它不知道,我怎么能得到任何时区的实际电流偏移量?在


Tags: 代码importdatetimeprintsnow偏移量totalseconds
1条回答
网友
1楼 · 发布于 2024-09-27 00:11:56

I assume the previous code is not aware of the political decisions of each country regarding DST and probably gets you the offset according to fixed DST dates or something like that.

你的假设是不正确的。时区的政治变化通过TZ Database记录和分配。然后,这些更改将在数百个不同的库、平台和操作系统中实现,比如您提到的pytz库。在

您描述的对America/Santiago的更改反映在TZDB 2016c中,后者在{a3}中实现。如果您使用的是pytz 2016.3或更高版本,那么您的代码会意识到这一变化。在

Pytz没问题,但您可能需要考虑改用dateutilVersion 2.5.2或更高版本具有此数据。在

相关问题 更多 >

    热门问题