Find the timezone & local time of your visitors using Python
In a previous post we had discussed the importance of personalization of the content of your website / mobile app based on the local time of your user. In this post, we will learn how to implement that using Python (if you need a code snippet in a different language, please contact us).
Prerequisites:
- The ipapi.co API for fetching the timezone
- Python 3.x
datetime
,pytz
andrequests
module
Step 1: Install the required modules via pip
pip install requests pytz
Step 2: Import Required Libraries
Let’s start by importing the necessary libraries.
import requests
from datetime import datetime
import pytz
Step 3: Fetch Timezone from ipapi
Assuming the user’s IP address is known or can be inferred from the API endpoint, we’ll retrieve the timezone using the API.
Get your timezone (ouptut format is text)
response = requests.get('https://ipapi.co/timezone/')
user_timezone = response.text
or get the timezone of a specific IP
ip = '8.8.8.8'
response = requests.get('https://ipapi.co/{}/timezone/'.format(ip))
user_timezone = response.text
Alternative output format (JSON)
response = requests.get('https://ipapi.co/json/')
location_data = response.json()
try:
user_timezone = location_data['timezone']
except Exception as e:
print(e)
Step 4: Compute Local Time
With the user’s timezone in hand, we can now calculate and display the accurate local time.
# Get the timezone object using pytz
timezone_obj = pytz.timezone(user_timezone)
# Get the current time in the user's timezone
current_time = datetime.now(timezone_obj)
# Display the time zone
print("User's timezone: {}".format(user_timezone))
>>> User's timezone: America/Los_Angeles
# Display the time zone
print("User's timezone: {}".format(user_timezone))
>>> Current local time: 2023–08–28 22:07:22 PDT
You can read more about the API at https://ipapi.co/api/