本文介绍了从UTC偏移量获取时区名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从Python中给定的UTC偏移量获取时区名称?
How can I get the timezone name from a given UTC offset in Python?
例如,我有
"GMT+0530"
我想要得到,
"Asia/Calcutta"
如果存在多个匹配项,则结果应为时区名称列表。
If there are multiple matches, the result should be a list of timezone names.
推荐答案
可能存在 零个或更多 (多个)时区,它们对应于 单个UTC偏移量 。要立即查找具有给定UTC偏移量的这些时区:
There could be zero or more (multiple) timezones that correspond to a single UTC offset. To find these timezones that have a given UTC offset now:
#!/usr/bin/env python
from datetime import datetime, timedelta
import pytz # $ pip install pytz
utc_offset = timedelta(hours=5, minutes=30) # +5:30
now = datetime.now(pytz.utc) # current time
print({tz.zone for tz in map(pytz.timezone, pytz.all_timezones_set)
if now.astimezone(tz).utcoffset() == utc_offset})
输出
Output
set(['Asia/Colombo', 'Asia/Calcutta', 'Asia/Kolkata'])
如果要考虑历史数据(根据当前时区规则在某个日期具有/将具有给定utc偏移量的时区):
If you want to take historical data into account (timezones that had/will have a given utc offset at some date according to the current time zone rules):
#!/usr/bin/env python
from datetime import datetime, timedelta
import pytz # $ pip install pytz
utc_offset = timedelta(hours=5, minutes=30) # +5:30
names = set()
now = datetime.now(pytz.utc)
for tz in map(pytz.timezone, pytz.all_timezones_set):
dt = now.astimezone(tz)
tzinfos = getattr(tz, '_tzinfos',
[(dt.utcoffset(), dt.dst(), dt.tzname())])
if any(off == utc_offset for off, _, _ in tzinfos):
names.add(tz.zone)
print("\n".join(sorted(names)))
输出
Output
Asia/Calcutta
Asia/Colombo
Asia/Dacca
Asia/Dhaka
Asia/Karachi
Asia/Kathmandu
Asia/Katmandu
Asia/Kolkata
Asia/Thimbu
Asia/Thimphu
这篇关于从UTC偏移量获取时区名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!