Getting Time from an IP Address with Python
There are many ways to obtain the current timezone from an IP Address. One is by using a database, and looking up the address. This is an effective way, but the database must be updated frequently. Another way is by using an API that displays location information (and timezone) from a given IP. And this is what I will show you in this post.
Actually, I built a web application that needs the visitor’s current date. And after a couple of hours of googling, I found a reliable API that can help me, IPInfoDB.
The API is pretty simple, and it’s free (registration required). To use it, just pass your API key and the IP address you want to lookup.
http://api.ipinfodb.com/v2/ip_query.php?key=<your_api_key>&ip=75.125.71.106&output=json&timezone=true
It will return something like:
{
"Status" : "OK",
"CountryCode" : "US",
"CountryName" : "United States",
"RegionCode" : "48",
"RegionName" : "Texas",
"City" : "Houston",
"ZipPostalCode" : "77002",
"Latitude" : "29.7523",
"Longitude" : "-95.367",
"Gmtoffset" : "-21600",
"Dstoffset" : "0",
"TimezoneName" : "America/Chicago",
"Isdst" : "0",
"Ip" : "75.125.71.106"
}
Now, it gave us enough data to accomplish our task. Well actually, the only data we need is Gmtoffset. The next thing we do is add that to the current UTC time. We can do that in Python:
>>> import datetime
>>> gmtoffset = '-21600'
>>> utctime = datetime.datetime.utcnow()
>>> utctime.strftime('%X %x')
'06:37:48 02/10/11'
>>> iptime = utctime + datetime.timedelta(0, int(gmtoffset))
>>> iptime.strftime('%X %x')
'00:37:48 02/10/11'
Take note that the GMT offset is given in seconds. And if we will convert -21600 seconds to hours, we will have exactly, -6 hours. The datetime.timedelta() method made the addition possible for us, and we just have to supply the number of seconds to add.
