我想知道我的用户发送请求的当地时间。 基本上,有这样的功能吗
var localTime = getLocalTime( lat, long );
我不确定lat上的简单划分是否可行,因为大多数国家都没有完美的几何形状。
任何帮助都会很棒。任何语言都被接受。我想避免调用远程API。
答案 0 :(得分:4)
Google Time Zone API似乎就是你所追求的。但它没有free tier。
时区API为地球表面上的位置提供时间偏移数据。请求特定纬度/经度对的时区信息将返回该时区的名称,与UTC的时间偏移以及夏令时偏移量。
答案 1 :(得分:3)
用于计算时区的shapefile已经not maintained了。
我今天刚遇到同样的问题,而且我不确定我的回答是多么相关,但我基本上只是编写了一个能够做你想要的Python函数。你可以在这里找到它。
https://github.com/cstich/gpstotz
编辑:
如评论中所述,我也应该发布代码。该代码基于Eric Muller的时区shapefile,你可以在这里找到它 - http://efele.net/maps/tz/world/。
编辑2:
事实证明,shapefile对外圈和内圈有一些古老的定义(基本上外圈采用右手规则,而内圈采用左手法则)。无论如何,fiona似乎会照顾到这一点,并相应地更新了代码。
from rtree import index # requires libspatialindex-c3.deb
from shapely.geometry import Polygon
from shapely.geometry import Point
import os
import fiona
''' Read the world timezone shapefile '''
tzshpFN = os.path.join(os.path.dirname(__file__),
'resources/world/tz_world.shp')
''' Build the geo-index '''
idx = index.Index()
with fiona.open(tzshpFN) as shapes:
for i, shape in enumerate(shapes):
assert shape['geometry']['type'] == 'Polygon'
exterior = shape['geometry']['coordinates'][0]
interior = shape['geometry']['coordinates'][1:]
record = shape['properties']['TZID']
poly = Polygon(exterior, interior)
idx.insert(i, poly.bounds, obj=(i, record, poly))
def gpsToTimezone(lat, lon):
'''
For a pair of lat, lon coordiantes returns the appropriate timezone info.
If a point is on a timezone boundary, then this point is not within the
timezone as it is on the boundary. Does not deal with maritime points.
For a discussion of those see here:
http://efele.net/maps/tz/world/
@lat: latitude
@lon: longitude
@return: Timezone info string
'''
query = [n.object for n in idx.intersection((lon, lat, lon, lat),
objects=True)]
queryPoint = Point(lon, lat)
result = [q[1] for q in query
if q[2].contains(queryPoint)]
if len(result) > 0:
return result[0]
else:
return None
if __name__ == "__main__":
''' Tests '''
assert gpsToTimezone(0, 0) is None # In the ocean somewhere
assert gpsToTimezone(51.50, 0.12) == 'Europe/London'
答案 2 :(得分:2)
我几天前正在寻找同样的事情,不幸的是我找不到API或简单的功能。正如你所说的那样,国家没有完美的几何形状。您必须创建每个时区区域的表示,并查看您的点所在的位置。我认为这将是一个痛苦,我不知道它是否可以完成。
我找到的唯一一个在这里描述:Determine timezone from latitude/longitude without using web services like Geonames.org。基本上你需要一个包含时区信息的数据库,你正试图看看哪一个最接近你的兴趣点。
但是,我一直在寻找静态解决方案(不使用互联网),所以如果你可以使用互联网连接,你可以使用:http://www.earthtools.org/webservices.htm提供一个web服务,为你提供给定纬度/经度坐标的时区。
答案 3 :(得分:0)
从2019年开始,Google API没有免费层,并且@cstich答案的数据源也不再维护。
如果您需要API,timezonedb.com提供的免费套餐速率限制为1个请求/秒。
@cstich所使用的数据的原始维护者链接到this project,后者从OpenStreetMap检索数据。自述文件包含用于以多种语言查找库的链接。
答案 4 :(得分:-4)
难道您不能简单地使用用户IP来确定他们居住的地方吗?然后你使用(Countries |与GMT的差异)数组来获得当地时间。