从Lat-Long坐标获取时区?

2024-04-23 16:49:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取纬度和经度坐标的时区,但遇到了一些问题 这些错误可能是非常基本的

我在数据库中有一个大约600行的表。每行包含一个世界某个地方的lat-long坐标 我想把这些坐标输入一个函数,然后检索时区。其目的是将这600个地点中每个地点都有本地时间戳的事件转换为UTC时间

我找到了一个blog post,它使用a piece of code从地理坐标推导时区

当我试图运行代码时,我得到了错误geonames is not defined。我已经申请了一个有地理名称的账户

我想我只是把函数文件保存在了错误的目录中或是简单的地方。有人能帮忙吗

#-------------------------------------------------------------------------------
# Converts latitude longitude into a time zone
# REF: https://gist.github.com/pamelafox/2288222
# REF: http://blog.pamelafox.org/2012/04/converting-addresses-to-timezones-in.html
#-------------------------------------------------------------------------------

geonames_client = geonames.GeonamesClient('Username_alpha')
geonames_result = geonames_client.find_timezone({'lat': 48.871236, 'lng': 2.77928})
user.timezone = geonames_result['timezoneId']

Tags: 函数clientref地方错误时间blogresult
1条回答
网友
1楼 · 发布于 2024-04-23 16:49:29

这与预期的效果一样:

import geonames
geonames_client = geonames.GeonamesClient('demo')
geonames_result = geonames_client.find_timezone({'lat': 48.871236, 'lng': 2.77928})
print geonames_result['timezoneId']

输出:

'Europe/Paris'
网友
2楼 · 发布于 2024-04-23 16:49:29

我能够使用timezonefinder执行适合我的目的的查找:

import datetime
import timezonefinder, pytz

tf = timezonefinder.TimezoneFinder()

# From the lat/long, get the tz-database-style time zone name (e.g. 'America/Vancouver') or None
timezone_str = tf.certain_timezone_at(lat=49.2827, lng=-123.1207)

if timezone_str is None:
    print "Could not determine the time zone"
else:
    # Display the current time in that time zone
    timezone = pytz.timezone(timezone_str)
    dt = datetime.datetime.utcnow()
    print "The time in %s is %s" % (timezone_str, dt + timezone.utcoffset(dt))

its pypi page链接的文档中讨论了timezonefinder的方法及其局限性

timezonefinderpytz可以在同名的pip包中找到

网友
3楼 · 发布于 2024-04-23 16:49:29

使用tzwhere和pytz:

import datetime
import pytz
from tzwhere import tzwhere

tzwhere = tzwhere.tzwhere()
timezone_str = tzwhere.tzNameAt(37.3880961, -5.9823299) # Seville coordinates
timezone_str
#> Europe/Madrid

timezone = pytz.timezone(timezone_str)
dt = datetime.datetime.now()
timezone.utcoffset(dt)
#> datetime.timedelta(0, 7200)

相关问题 更多 >