gpt4 book ai didi

python - 在 Python/Django 中从城市获取时区

转载 作者:太空狗 更新时间:2023-10-29 17:02:34 25 4
gpt4 key购买 nike

使用 pytz,我能够像这样获得时区列表:

>>> from pytz import country_timezones
>>> print(' '.join(country_timezones('ch')))
Europe/Zurich
>>> print(' '.join(country_timezones('CH')))
Europe/Zurich

鉴于我从用户那里获得了国家和城市字段,我该如何确定城市的时区?

最佳答案

pytz 是 IANA 时区数据库(Olson 数据库)的包装器。它不包含将世界上任意城市映射到它所在时区的数据。

您可能需要一个地理编码器,例如 geopy可以使用各种网络服务将地点(例如城市名称)转换为其坐标(纬度、经度):

from geopy import geocoders # pip install geopy

g = geocoders.GoogleV3()
place, (lat, lng) = g.geocode('Singapore')
# -> (u'Singapore', (1.352083, 103.819836))

给定城市的纬度、经度,可以使用 tz_world, an efele.net/tz map / a shapefile of the TZ timezones of the world 找到它的时区例如,通过 postgis timezone dbpytzwhere :

import tzwhere

w = tzwhere()
print w.tzNameAt(1.352083, 103.819836)
# -> Asia/Singapore

还有允许将(纬度、经度)转换为时区的网络服务,例如 askgeo , geonames , 请参阅 Timezone lookup from latitude longitude .

作为@dashesy pointed out in the comment , geopy 也可以找到时区(自 1.2 起):

timezone = g.timezone((lat, lng)) # return pytz timezone object
# -> <DstTzInfo 'Asia/Singapore' LMT+6:55:00 STD>

GeoNames also provides offline data允许直接从其名称获取城市的时区,例如:

#!/usr/bin/env python
import os
from collections import defaultdict
from datetime import datetime
from urllib import urlretrieve
from urlparse import urljoin
from zipfile import ZipFile

import pytz # pip install pytz

geonames_url = 'http://download.geonames.org/export/dump/'
basename = 'cities15000' # all cities with a population > 15000 or capitals
filename = basename + '.zip'

# get file
if not os.path.exists(filename):
urlretrieve(urljoin(geonames_url, filename), filename)

# parse it
city2tz = defaultdict(set)
with ZipFile(filename) as zf, zf.open(basename + '.txt') as file:
for line in file:
fields = line.split(b'\t')
if fields: # geoname table http://download.geonames.org/export/dump/
name, asciiname, alternatenames = fields[1:4]
timezone = fields[-2].decode('utf-8').strip()
if timezone:
for city in [name, asciiname] + alternatenames.split(b','):
city = city.decode('utf-8').strip()
if city:
city2tz[city].add(timezone)

print("Number of available city names (with aliases): %d" % len(city2tz))

#
n = sum((len(timezones) > 1) for city, timezones in city2tz.iteritems())
print("")
print("Find number of ambigious city names\n "
"(that have more than one associated timezone): %d" % n)

#
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
city = "Zurich"
for tzname in city2tz[city]:
now = datetime.now(pytz.timezone(tzname))
print("")
print("%s is in %s timezone" % (city, tzname))
print("Current time in %s is %s" % (city, now.strftime(fmt)))

输出

Number of available city names (with aliases): 112682

Find number of ambigious city names
(that have more than one associated timezone): 2318

Zurich is in Europe/Zurich timezone
Current time in Zurich is 2013-05-13 11:36:33 CEST+0200

关于python - 在 Python/Django 中从城市获取时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16505501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com