Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Get Time Zone of a Given Location using Python

  • Last Updated : 29 Nov, 2021

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

  1. 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:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!