How to get a Timezone from a Location in Python

12.06.2020

Intro

A common problem when building websites is knowing the timezone of your users. Sometimes you collect an address, but did not specifically ask for a timezone. In this lesson, we will learn how to turn addresses or locations into timezones.

Installing Modules

We will need two modules for this task. geopy, which can use the OpenStreetMap project to reverse geocode (give us coordinates), and timezonefinder which can take those coordinates and return a timezone. Begin by install poth of these.

pip install geopy timezonefinder

Geopy

Let's start with geopy. We first need to create an instance of a Nominatim class from the geopy library, then we can use the geocode function to get coordinates from a location string.

from geopy.geocoders import Nominatim

geolocator = Nominatim(user_agent="anyName")
coords = geolocator.gecode("Dallas, Texas")

print(coords.latitude, coords.longitude)

TimezoneFinder

Now that we have our coordinates, we can use timezonefinder. First we create a TimezoneFinder object, then we use the timezone_at function.

from timezonefinder import TimezoneFinder

tf = TimezoneFinder()

timezone = tf.timezone_at(lng=coords.longitude, lat=coords.latitude)
print(timezone)

The Full Example

Let's finish by putting everyting together.

from geopy.geocoders import Nominatim
from timezonefinder import TimezoneFinder

geolocator = Nominatim(user_agent="anyName")
tf = TimezoneFinder()

coords = geolocator.gecode("Dallas, Texas")
tf = TimezoneFinder()
timezone = tf.timezone_at(lng=coords.longitude, lat=coords.latitude)
print(timezone)