In this article, we are going to see how to get the time zone from a given location. The Timezonefinder module is able to find the timezone of any point on earth (coordinates) offline. Before starting we need to install this module.
Modules Needed
- timezonefinder: This module does not built in with Python. To install this type the below command in the terminal.
pip install timezonefinder
- Geopy: .geopy makes it easy for Python developers to locate the coordinates of addresses, cities, countries, and landmarks across the world. To install the Geopy module, run the following command in your terminal.
pip install geopy
Let’s understand this module with Step by step:
Step 1: import TimezoneFinder module
Python3
from timezonefinder import TimezoneFinder |
Step 2: make an object of TimezoneFinder.
Python3
# object creation obj = TimezoneFinder() |
Step 3: Pass the latitude and longitude in a timezone_at() method and it return the time zone of a given location.
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) |
Output:
'Asia/Kolkata'
Now let write a script to get timezone with a specific location.
Approach:
- Import the module
- Initialize Nominatim API to get location from the input string.
- Get latitude and longitude with geolocator.geocode() function.
- Pass the latitude and longitude in a timezone_at() method and it returns the time zone of a given location.
Code:
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 Longitude location = geolocator.geocode(lad) print ( "Latitude and Longitude of the said address:" ) print ((location.latitude, location.longitude)) # pass the Latitude and Longitude # 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) |
Output:
Location address: Dhaka Latitude and Longitude of the said address: (23.810651, 90.4126466) Time Zone : Asia/Dhaka