Search code examples
pythonphone-numberlibphonenumberphonenumberutils

Get matched region for a number in python's phonenumbers library


I am using python's phonenumbers library to parse and validate numbers like this:

>> import phonenumbers
>>> x = phonenumbers.parse("+442083661177")
>>> print x
Country Code: 44 National Number: 2083661177 Leading Zero: False

And wanted to know that if there is any possible way to get the matched the 2-letter Region for given number for further use?

I have tried this method, which is mentioned in Readme:

>>> from phonenumbers import timezone
>>> gb_number = phonenumbers.parse("+447986123456")
>>> list(timezone.time_zones_for_number(gb_number))
['Europe/London']

But the problem is I can not find a way to parse another number using these timezones. (phonenumbers.parse("07986123456", 'Europe/London') will throw an exception)


Solution

  • You need to get the country code first rather than the timezone:

    >>> gb_number = phonenumbers.parse("+447986123456")
    >>> cc = phonenumbers.region_code_for_number(gb_number)
    >>> cc
    'GB'
    >>> phonenumbers.parse("07986123456", cc)
    PhoneNumber(country_code=44, national_number=7986123456, extension=None, italian_leading_zero=None, number_of_leading_zeros=None, country_code_source=None, preferred_domestic_carrier_code=None)
    

    This is because many countries have different dial codes but the same time-zone.