What python libraries can tell me approximate location and time zone given an IP address?

Looking to implement better geo-location with Python.


Solution 1:

Hostip.info is an open-source project with the goal to build/maintain a database mapping IP addresses to cities. Their about page explains the data sources relied on to populate this database.

Using HostIP, there are two ways to get location data from an IP address:

They also have a well-designed and easy-to-use RESTFUL API: just pass in your ip address after the i***p=*** in the GET request string):

import urllib

response = urllib.urlopen('http://api.hostip.info/get_html.php?ip=12.215.42.19&position=true').read()

print(response)

Second, the Project Website also makes its complete database available for download.

Solution 2:

It is not a Python lib. But http://ipinfodb.com/ provides a webservice that can be easily wrapped by Python code with urllib for example.

http://api.ipinfodb.com/v3/ip-city/?key=<your_api_key>&ip=74.125.45.100
http://api.ipinfodb.com/v3/ip-country/?key=<your_api_key>&ip=74.125.45.100

You need to request a free API key. See the API doc for details.

Solution 3:

You may find these modules useful: MaxMind's GeoIP and its pure version, as well pytz.

Solution 4:

I posted this in another question that had been buried, but linked here:

#!/usr/bin/env python 
from urllib2 import urlopen
from contextlib import closing
import json

# Automatically geolocate the connecting IP
url = 'http://freegeoip.net/json/'
try:
    with closing(urlopen(url)) as response:
        location = json.loads(response.read())
        print(location)
        location_city = location['city']
        location_state = location['region_name']
        location_country = location['country_name']
        location_zip = location['zipcode']
except:
    print("Location could not be determined automatically")

Send HTTP GET requests to: freegeoip.net/{format}/{ip_or_hostname} to receive a JSON output that Python can parse.

I get the following JSON keys, which should be sufficient for what you are needing:

  • ip
  • country_code
  • country_name
  • region_code
  • region_name
  • city
  • zipcode
  • latitude
  • longitude
  • metro_code
  • area_code

Solution 5:

Found https://freegeoip.net/; python sample below.

import requests

FREEGEOPIP_URL = 'http://freegeoip.net/json/'

SAMPLE_RESPONSE = """{
    "ip":"108.46.131.77",
    "country_code":"US",
    "country_name":"United States",
    "region_code":"NY",
    "region_name":"New York",
    "city":"Brooklyn",
    "zip_code":"11249",
    "time_zone":"America/New_York",
    "latitude":40.645,
    "longitude":-73.945,
    "metro_code":501
}"""


def get_geolocation_for_ip(ip):
    url = '{}/{}'.format(FREEGEOPIP_URL, ip)

    response = requests.get(url)
    response.raise_for_status()

    return response.json()