使用Python获取给定位置的时区
在本文中,我们将了解如何从给定位置获取时区。 Timezonefinder模块能够离线查找地球上任何一点(坐标)的时区。在开始之前,我们需要安装这个模块。
需要的模块
- timezonefinder:这个模块不是用Python内置的。要安装此类型,请在终端中输入以下命令。
pip install timezonefinder
- Geopy: .geopy 使Python开发人员可以轻松定位全球地址、城市、国家和地标的坐标。要安装 Geopy 模块,请在终端中运行以下命令。
pip install geopy
让我们一步一步地理解这个模块:
第 1 步:导入 TimezoneFinder 模块
Python3
from timezonefinder import TimezoneFinder
Python3
# object creation
obj = TimezoneFinder()
Python3
# pass the longitude and latitude
# in timezone_at and
# it return time zone
latitude = 25.6093239
longitude = 85.1235252
obj.timezone_at(lng=latitude, lat=longitude)
Python3
# importing module
from geopy.geocoders import Nominatim
from timezonefinder import TimezoneFinder
# initialize Nominatim API
geolocator = Nominatim(user_agent="geoapiExercises")
# input as a geek
lad = "Dhaka"
print("Location address:", lad)
# getting Latitude and Longitud
location = geolocator.geocode(lad)
print("Latitude and Longitude of the said address:")
print((location.latitude, location.longitude))
# pass the Latitude and Longitud
# into a timezone_at
# and it return timezone
obj = TimezoneFinder()
# returns 'Europe/Berlin'
result = obj.timezone_at(lng=location.longitude, lat=location.latitude)
print("Time Zone : ", result)
第 2 步:创建 TimezoneFinder 的对象。
蟒蛇3
# object creation
obj = TimezoneFinder()
第 3 步:在 timezone_at() 方法中传递纬度和经度,并返回给定位置的时区。
蟒蛇3
# pass the longitude and latitude
# in timezone_at and
# it return time zone
latitude = 25.6093239
longitude = 85.1235252
obj.timezone_at(lng=latitude, lat=longitude)
输出:
'Asia/Kolkata'
现在让我们编写一个脚本来获取具有特定位置的时区。
方法:
- 导入模块
- 初始化 Nominatim API 以从输入字符串中获取位置。
- 使用 geolocator.geocode()函数获取纬度和经度。
- 在 timezone_at() 方法中传递纬度和经度,并返回给定位置的时区。
代码:
蟒蛇3
# importing module
from geopy.geocoders import Nominatim
from timezonefinder import TimezoneFinder
# initialize Nominatim API
geolocator = Nominatim(user_agent="geoapiExercises")
# input as a geek
lad = "Dhaka"
print("Location address:", lad)
# getting Latitude and Longitud
location = geolocator.geocode(lad)
print("Latitude and Longitude of the said address:")
print((location.latitude, location.longitude))
# pass the Latitude and Longitud
# into a timezone_at
# and it return timezone
obj = TimezoneFinder()
# returns 'Europe/Berlin'
result = obj.timezone_at(lng=location.longitude, lat=location.latitude)
print("Time Zone : ", result)
输出:
Location address: Dhaka
Latitude and Longitude of the said address:
(23.810651, 90.4126466)
Time Zone : Asia/Dhaka