我在我的数据库中为用户存储了UTC偏移量:
+5:30
如何使用Python从UTC偏移量获取时区缩写?
例如:
+5:30 => IST
使用Python实现这个目标是否可行?
我在我的数据库中为用户存储了UTC偏移量:
+5:30
+5:30 => IST
使用Python实现这个目标是否可行?
#!/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({now.astimezone(tz).tzname()
for tz in map(pytz.timezone, pytz.all_timezones_set)
if now.astimezone(tz).utcoffset() == utc_offset})
set(['IST'])
如果您想获取包括历史数据在内的缩写:
#!/usr/bin/env python
from datetime import datetime, timedelta
import pytz # $ pip install pytz
utc_offset = timedelta(hours=5, minutes=30) # +5:30
abbr = 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())])
abbr.update(tzname for off, _, tzname in tzinfos if off == utc_offset)
print(abbr)
set(['IST'])
tzdata
,然后以类似的方式使用zoneinfo.available_timezones()
,就像上面答案中使用pytz.all_timezones_set
一样。 - undefined正如Matt所指出的那样,从偏移量到时区并没有太多意义。
如果你想要为给定的偏移量找到一个合适的pytz.timezone对象:
有各种各样的时区,从"Etc/GMT-14"
到"Etc/GMT+12"
只需查看pytz.all_timezones
即可。
使用它们,我能够将错误的客户端输入(误将时区误认为是偏移量)用于给我的用户附加有效的时区对象。