使用pytz
,我可以得到一个时区列表,如下所示:
>>> from pytz import country_timezones
>>> print(' '.join(country_timezones('ch')))
Europe/Zurich
>>> print(' '.join(country_timezones('CH')))
Europe/Zurich
鉴于我从用户那里获得 Country 和 City 字段,我该如何确定城市的时区?
pytz
is a wrapper around IANA Time Zone Database (Olson database). It does not contain data to map an arbitrary city in the world to the timezone it is in.
You might need a geocoder such as geopy
that can translate a place (e.g., a city name) to its coordinates (latitude, longitude) using various web-services:
from geopy import geocoders # pip install geopy
g = geocoders.GoogleV3()
place, (lat, lng) = g.geocode('Singapore')
# -> (u'Singapore', (1.352083, 103.819836))
Given city's latitude, longitude, it is possible to find its timezone using tz_world, an efele.net/tz map / a shapefile of the TZ timezones of the world e.g., via postgis timezone db or pytzwhere
:
import tzwhere
w = tzwhere()
print w.tzNameAt(1.352083, 103.819836)
# -> Asia/Singapore
There are also web-services that allow to convert (latitude, longitude) into a timezone e.g., askgeo, geonames, see Timezone lookup from latitude longitude.
As @dashesy pointed out in the comment, geopy
also can find timezone (since 1.2):
timezone = g.timezone((lat, lng)) # return pytz timezone object
# -> <DstTzInfo 'Asia/Singapore' LMT+6:55:00 STD>
GeoNames also provides offline data that allows to get city's timezone directly from its name e.g.:
#!/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
这里提出了很多可能的解决方案,但设置起来都有些乏味。
为了让下一个遇到这个问题的人更快,我从 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
在示例中),因此您可以以 Python 方式使用它。
我认为您将需要手动搜索您要查找的城市的时区数据库:
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
,它会匹配子字符串,不搜索不区分大小写等)
这个想法是使用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将时区归因于给定的纬度/经度坐标。
没有简单的方法可以做到这一点,这是不幸的。Geonames 记录了每个城市的列表及其时区名称。这将是一个很好的选择,但是您必须围绕它解析和构建自己的数据库,这样您就可以随时轻松地从国家/城市对中找到时区。
我最终requests
通过使用和解析 JSON 的几个 Google API 调用解决了这个问题。我能够在没有 API 密钥的情况下做到这一点,因为我永远不会达到他们的使用限制。
https://gist.github.com/willcharlton/b055885e249a902402fc
我希望这有帮助。
@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