Python-phonenumbers

9.0.26 · active · verified Sun Mar 29

Python-phonenumbers is a Python port of Google's `libphonenumber` library, providing robust functionality for parsing, formatting, storing, and validating international phone numbers. It is actively maintained and regularly updated to reflect upstream changes from the original Java library. The current version is 9.0.26.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse, validate, format, and retrieve auxiliary information (carrier, region, timezone) for a phone number. It handles potential parsing errors using a try-except block.

import phonenumbers
from phonenumbers import geocoder, carrier, timezone, PhoneNumberFormat

# 1. Parse a phone number
#   - The second argument ('GB') provides a default region if the number is not in E.164 format.
#   - If the number is E.164 (e.g., '+44...'), None can be used as the default region.
phone_number_str = "+442083661177"
country_code = "GB" # Default region for parsing, if number is not in international format

try:
    parsed_number = phonenumbers.parse(phone_number_str, country_code)
    print(f"Parsed Number: {parsed_number}")

    # 2. Validate the phone number
    is_valid = phonenumbers.is_valid_number(parsed_number)
    is_possible = phonenumbers.is_possible_number(parsed_number)
    print(f"Is Valid: {is_valid}, Is Possible: {is_possible}")

    if is_valid:
        # 3. Format the phone number in various ways
        national_format = phonenumbers.format_number(parsed_number, PhoneNumberFormat.NATIONAL)
        international_format = phonenumbers.format_number(parsed_number, PhoneNumberFormat.INTERNATIONAL)
        e164_format = phonenumbers.format_number(parsed_number, PhoneNumberFormat.E164)

        print(f"National Format: {national_format}")
        print(f"International Format: {international_format}")
        print(f"E.164 Format: {e164_format}")

        # 4. Get carrier, region, and timezone information
        #    Note: These lookups depend on the data included in the phonenumbers library.
        carrier_name = carrier.name_for_number(parsed_number, "en")
        region_description = geocoder.description_for_number(parsed_number, "en")
        timezones = timezone.time_zones_for_number(parsed_number)

        print(f"Carrier: {carrier_name}")
        print(f"Region: {region_description}")
        print(f"Timezones: {timezones}")

except phonenumbers.NumberParseException as e:
    print(f"Error parsing number: {e}")

view raw JSON →