获取当地时区的Olson TZ名称?
如何获得与C
调用给出的值相对应的Olson时区名称(例如Australia/Sydney
)localtime
?
这是通过TZ
,通过符号链接/etc/localtime
或TIMEZONE
在与时间相关的系统配置文件中设置变量来覆盖的值。
回答:
我认为最好的选择是遍历所有pytz时区,并检查哪个匹配本地时区,每个pytz时区对象都包含有关utcoffset和tzname的信息,例如CDT,EST,可以从time.timezone/altzone
和获取有关本地时间的相同信息time.tzname
,我认为这是足以正确匹配pytz数据库中的本地时区,例如
import timeimport pytz
import datetime
local_names = []
if time.daylight:
local_offset = time.altzone
localtz = time.tzname[1]
else:
local_offset = time.timezone
localtz = time.tzname[0]
local_offset = datetime.timedelta(seconds=-local_offset)
for name in pytz.all_timezones:
timezone = pytz.timezone(name)
if not hasattr(timezone, '_tzinfos'):
continue#skip, if some timezone doesn't have info
# go thru tzinfo and see if short name like EDT and offset matches
for (utcoffset, daylight, tzname), _ in timezone._tzinfos.iteritems():
if utcoffset == local_offset and tzname == localtz:
local_names.append(name)
print local_names
输出:
[‘America/Atikokan’, ‘America/Bahia_Banderas’, ‘America/Bahia_Banderas’, ‘America/Belize’, ‘America/Cambridge_Bay’, ‘America/Cancun’, ‘America/Chicago’, ‘America/Chihuahua’, ‘America/Coral_Harbour’, ‘America/Costa_Rica’, ‘America/El_Salvador’, ‘America/Fort_Wayne’, ‘America/Guatemala’, ‘America/Indiana/Indianapolis’, ‘America/Indiana/Knox’, ‘America/Indiana/Marengo’, ‘America/Indiana/Marengo’, ‘America/Indiana/Petersburg’, ‘America/Indiana/Tell_City’, ‘America/Indiana/Vevay’, ‘America/Indiana/Vincennes’, ‘America/Indiana/Winamac’, ‘America/Indianapolis’, ‘America/Iqaluit’, ‘America/Kentucky/Louisville’, ‘America/Kentucky/Louisville’, ‘America/Kentucky/Monticello’, ‘America/Knox_IN’, ‘America/Louisville’, ‘America/Louisville’, ‘America/Managua’, ‘America/Matamoros’, ‘America/Menominee’, ‘America/Merida’, ‘America/Mexico_City’, ‘America/Monterrey’, ‘America/North_Dakota/Beulah’, ‘America/North_Dakota/Center’, ‘America/North_Dakota/New_Salem’, ‘America/Ojinaga’, ‘America/Pangnirtung’, ‘America/Rainy_River’, ‘America/Rankin_Inlet’, ‘America/Resolute’, ‘America/Resolute’, ‘America/Tegucigalpa’, ‘America/Winnipeg’, ‘CST6CDT’, ‘Canada/Central’, ‘Mexico/General’, ‘US/Central’, ‘US/East-Indiana’, ‘US/Indiana-Starke’]
在生产中,您可以预先创建这样的映射并保存它,而不必总是进行迭代。
更改时区后测试脚本:
$ export TZ=’Australia/Sydney’
$ python get_tz_names.py
[‘Antarctica/Macquarie’, ‘Australia/ACT’, ‘Australia/Brisbane’, ‘Australia/Canberra’, ‘Australia/Currie’, ‘Australia/Hobart’, ‘Australia/Lindeman’, ‘Australia/Melbourne’, ‘Australia/NSW’, ‘Australia/Queensland’, ‘Australia/Sydney’, ‘Australia/Tasmania’, ‘Australia/Victoria’]
以上是 获取当地时区的Olson TZ名称? 的全部内容, 来源链接: utcz.com/qa/407934.html