Some of you may have read my article about python-geoip for mapping an IP to a city.
If you provide a service which relies on timezones or even just want to display a message at that time then being able to map an IP address to a timezone can be valuable.
This assumes that you have the GeoLiteCity.dat database and that it’s all setup and working. I can show you how to do that in this article.
Once you have that all setup and working all you have to do to get the timezone is pass the country code and region to the GeoIP library function GeoIP.time_zone_by_country_and_region() function.
Here’s an example…
>>> import GeoIP
>>> GeoIP.time_zone_by_country_and_region(gi.record_by_addr("74.125.93.106")['country_code'], gi.record_by_addr("74.125.93.106")['region'])
'America/Los_Angeles'
PyTZ
PyTZ is a nice library that you can use to manipulate timezones in python.
If you want to find out the timezone for an IP address you’ll need to pass it through PyTZ.
>>> from pytz import timezone
>>> tz = timezone(GeoIP.time_zone_by_country_and_region(gi.record_by_addr("74.125.93.106")['country_code'], gi.record_by_addr("74.125.93.106")['region']))
Calculating Daylight Savings Time (DST)
>>> from datetime import datetime
>>> loc_dt = tz.localize(datetime(2011,5,26,16,0,0))
>>> loc_dt.dst()
datetime.timedelta(0, 3600)
>>> loc_dt = tz.localize(datetime(2011,12,26,16,0,0))
>>> loc_dt.dst()
datetime.timedelta(0)
Here you can see that on May 26th 2011 the DST 3600 seconds (an hour), then on December 26th 2011 the DST is 0.
Summary
So here’s the complete code for figuring out daylight savings time from an IP…
>>> import GeoIP
>>> from pytz import timezone
>>> from datetime import datetime
>>> gi = GeoIP.open("/usr/share/GeoIP/GeoIPCity.dat", GeoIP.GEOIP_STANDARD)
>>> googles_tz = GeoIP.time_zone_by_country_and_region(gi.record_by_addr("74.125.93.106")['country_code'], gi.record_by_addr("74.125.93.106")['region'])
>>> tz = timezone(googles_tz)
>>> loc_dt = tz.localize(datetime(2011,5,26,16,0,0))
>>> loc_dt.dst()
datetime.timedelta(0, 3600)
>>> loc_dt = tz.localize(datetime(2011,12,26,16,0,0))
>>> loc_dt.dst()
datetime.timedelta(0)