使用 pytz
我可以这样获取时区列表:
>>> from pytz import country_timezones
>>> print(' '.join(country_timezones('ch')))
Europe/Zurich
>>> print(' '.join(country_timezones('CH')))
Europe/Zurich
如果我从用户那里获取了国家和城市字段,我该如何确定该城市的时区?
pytz
是围绕IANA时区数据库(Olson数据库)的包装器。它不包含将世界上任意城市映射到所在时区的数据。
您可能需要一个地理编码器,例如geopy
,它可以使用各种Web服务将地点(例如城市名称)转换为其坐标(纬度,经度):
from geopy import geocoders # pip install geopy
g = geocoders.GoogleV3()
place, (lat, lng) = g.geocode('Singapore')
# -> (u'Singapore', (1.352083, 103.819836))
pytzwhere
来实现。这些都是关于世界各个时区形状文件的e-fele.net/tz地图。请注意:本文中保留原有的HTML标签,请勿删除。import tzwhere
w = tzwhere()
print w.tzNameAt(1.352083, 103.819836)
# -> Asia/Singapore
正如@dashesy在评论中指出的那样,geopy
也可以找到时区(自1.2版本以来):
timezone = g.timezone((lat, lng)) # return pytz timezone object
# -> <DstTzInfo 'Asia/Singapore' LMT+6:55:00 STD>
GeoNames还提供离线数据,可以直接通过城市名称获取所在时区,例如:
#!/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
geopy
本身可以找到时区:g.timezone(g.geocode('新加坡').point)
。 - dashesy这里提出了许多可能的解决方案,但都有一些繁琐的设置。
为了让下一个遇到这个问题的人更快地解决,我采用了Will Charlton提供的方案,并快速制作了一个Python库:https://pypi.python.org/pypi/whenareyou
from whenareyou import whenareyou
tz = whenareyou('Hamburg')
tz.localize(datetime(2002, 10, 27, 6, 0, 0))
获取的是 datetime.datetime(2002, 10, 27, 6, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CET+1:00:00 STD>)
。
这将为您提供一个 pytz 对象(在示例中为 tz
),以便您可以使用它的 Pythonic 方法。
ImportError: 无法从'requests.packages.urllib3.util.url'导入'_normalize_host'名称
。 - Ricky Levi通过geopy的地理编码器之一,查找给定城市(或州)的纬度/经度坐标,并从地理编码器获取适当的时区。
from datetime import datetime, timezone
from geopy import geocoders
# get the location by using one of the geocoders.
# GeoNames has a free option.
gn = geopy.geocoders.GeoNames(username='your-account-name')
loc = gn.geocode("California, USA")
# some geocoders can obtain the time zone directly.
# note: the geopy.timezone object contains a pytz timezone.
loc_tz = gn.reverse_timezone(loc.point)
# EXAMPLE: localize a datetime object
dt_UTC = datetime(2020, 11, 27, 12, 0, 0, tzinfo=timezone.utc)
dt_tz = dt_UTC.astimezone(loc_tz.pytz_timezone)
print(dt_tz, repr(dt_tz))
# 2020-11-27 04:00:00-08:00
# datetime.datetime(2020, 11, 27, 4, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)
timezonefinder
只能使用纬度和经度。而且 geopy 目前无法使用(截至印度标准时间 7 月 1 日下午 2 点),因此我无法注册用户名。有没有其他替代方案?谢谢。 - Naveen Reddy Marthala我认为你需要手动搜索时区数据库以查找你所需要的城市:
from pytz import country_timezones, timezone
def find_city(query):
for country, cities in country_timezones.items():
for city in cities:
if query in city:
yield timezone(city)
for tz in find_city('Zurich'):
print(tz)
Europe
,它进行了子字符串匹配,不区分大小写等。)pytz
提供的时区数据库中的城市。 - robertklep我最终使用了几个谷歌API调用,使用requests
并解析JSON来解决这个问题。我能够不使用API密钥完成它,因为我永远不会达到他们的使用限制。
https://gist.github.com/willcharlton/b055885e249a902402fc
我希望这能有所帮助。
from geopy.geocoders import Nominatim
from timezonefinder import TimezoneFinder
geolocator = Nominatim(user_agent="anyName")
tf = TimezoneFinder()
coords = geolocator.gecode("Dallas, Texas")
tf = TimezoneFinder()
timezone = tf.timezone_at(lng=coords.longitude, lat=coords.latitude) 更多细节请点击这里
@robertklep的方法可能有效。
但是这里有另一种可能的方法,使用astral
- https://pypi.python.org/pypi/astral/0.5
>>> import datetime
>>> from astral import Astral
>>> city_name = 'London' # assuming we retrieve this from user input
>>> a = Astral()
>>> a.solar_depression = 'civil'
>>> city = a[city_name] # creates the city object given the city name above
>>> print('Information for %s/%s\n' % (city_name, city.country))
Information for London/England
>>> timezone = city.timezone
>>> print('Timezone: %s' % timezone)
Timezone: Europe/London
Europe/Zurich
的时区? - robertklep