Python Code to Track Phone Number Location

Introduction

In this tutorial, we will look at a Python code to track phone number location. Python provides a package known as phonenumbers to do tasks related to phone number tracking internationally. We will learn about this package and write a code to understand how its features are used to do the location tracking of any given phone number(s).

 

Python Code to Track Phone Number Location - linuxnasa

Phonenumbers Module Overview

The ‘phonenumbers’  module in Python is a library for parsing, formatting and validating phone numbers. It allows you to work with phone numbers in various formats end extract information such as the country of origin, carrier (service provider), timezone and more. this module is particularly useful when dealing with phone number-related tasks in applications including:

  • Parsing and Validating  Phone numbers.
  • Formatting Phone Numbers
  • Geolocation (Country Information)
  • Carrier Information
  • Timezone Information
  • Number Type Identification
  • Number Normalization

 

Python Code to Track Phone Number Location – linuxnasa

Also read: Top 20 Python Lambda Function Interview Questions and Answers (2023)

Now that we know the usage of phonenumbers module in Python, Let us now use some of this module’s in-built function to implement the modules features.  We have written a code below in which we have provided two phone numbers as input. This code will process the given phone numbers and  return the tracking information related to each of these phone numbers. Let us look at the code below.

Prerequisite

  • Any Python IDE on Windows
  • Python installed
  • Basic understanding of Python

 

import phonenumbers
from phonenumbers import geocoder, carrier, timezone

def track_phone_location(phone_number):

    try:
        parsed_number = phonenumbers.parse(phone_number, None)
        if not phonenumbers.is_valid_number(parsed_number):
            return "Invalid phone number"

        # Get the country information
        country_info = geocoder.description_for_number(parsed_number, "en")

        # Get the timezone
        time_info = timezone.time_zones_for_number(parsed_number)

        # Join the time zones into a comma-separated string
        time_zones = ", ".join(time_info)

        # Get the carrier (service provider) information
        carrier_info = carrier.name_for_number(parsed_number, "en")
        return f"Country: {country_info}\nCarrier: {carrier_info}\nTimezone: {time_zones}"

    except phonenumbers.phonenumberutil.NumberFormatError:
        return "Invalid phone number format"

    except Exception as e:
        return f"Error: {str(e)}"

phone_number1 = "+919431162345"
phone_number2 = "+447986123456"

print("\nPhone Numbers Location\n")
result1 = track_phone_location(phone_number1)
result2 = track_phone_location(phone_number2)

print(f"Phone Number 1:\n{result1}\n")
print(f"Phone Number 2:\n{result2}\n")
OUTPUT
PS C:\Users\linuxnasa\Desktop\python_projects> python .\phoneNumberLocationTracker.py

Phone Numbers Location

Phone Number 1:
Country: India
Carrier: BSNL MOBILE
Timezone: Asia/Calcutta

Phone Number 2:
Country: United Kingdom
Carrier: EE
Timezone: Europe/Guernsey, Europe/Isle_of_Man, Europe/Jersey, Europe/London

 

NOTE:

To install phoneumbers module, use the command ‘pip install phonenumbers‘.

 

Code Explanation

The above Python code tracks the location, carrier and timezone of two given phone numbers using the ‘phonenumbers’ library.  Here is the end to end flow of the code.

1.  Import Required Libraries:  The script imports the necessary functions and classes from the ‘phonenumbers’ library. This library is used for working with phone numbers, including parsing, validation and extracting information.

2.  Define the ‘track_phone_location‘ function:  This function takes a phone number as input and performs the following steps.

  • Parse the input phone number using ‘phonenumbers.parse’.
  • Check if the parsed number is valid using ‘phonenumbers.is_valid_number‘. If it’s not valid, return “Invalid phone number.”
  • Get the country information (geolocation) for the phone number using ‘geocoder.description_for_number’.
  • Get the timezone information for the phone number using ‘timezone.time_zones_for_number’ and join the time zones into a comma separated string.
  • Get the carrier (service provider) information for the phone number using ‘carrier.name_for_number
  • Return a formatted string containing the country, carrier and timezone information.

3.  Exception Handling:  The function includes exception handling to capture specific errors.

  • phonenumbers.phonenumberutil.NumberFormatError‘:  If the phone number format is invalid, it returns “Invalid phone number format”.
  • Generic ‘Exception’:  If any other unexpected error occurs, it returns an error message with the details.

4.  Define Two Phone Numbers:   Two phone numbers, ‘phone_number1’ and ‘phone_number2’ are defined as strings. These numbers represent international phone numbers with country codes.

5.  Track Phone Number Locations:  The script calls the ‘track_phone_location’ function for both ‘phone_number1’ and ‘phone_number2’. It stores the results in the ‘result1’ and ‘result2’ variables.

6.  Print Results:  Finally, he script prints the results, including the country, carrier and timezone information for both phone numbers.

 

Summary

Learn more about how to install and use ‘phonenumbers’ module in Python from pypi.org.

 

Leave a Comment