In my recent django project, I needed to show timestamps in user's timezone. I thought it will be easier. But it took some time for me to figure out it. I'm listing the steps I followed to achieve that. This may help someone.
Packages/Services used
- Python requests - 2.8.1
- pytz - 2015.7
- API of freegeoip.net
Step 1: Get user timezone
You can get user timezone from freegeoip API by making a get request to the API.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
.... | |
freegeoip_response = requests.get('http://freegeoip.net/json') | |
freegeoip_response_json = freegeoip_response.json() | |
user_time_zone = freegeoip_response_json['time_zone'] |
Step 2: Activate timezone
Then activate the timezone using the command
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pytz | |
from django.utils import timezone | |
.... | |
timezone.activate(pytz.timezone(user_time_zone)) |
You can write a middleware to do this so that the timezone is activated. The middleware code can be like this.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserTimezoneMiddleware(object): | |
""" Middleware to check user timezone. """ | |
def process_request(self, request): | |
user_time_zone = request.session.get('user_time_zone', None) | |
try: | |
if user_time_zone is None: | |
freegeoip_response = requests.get('http://freegeoip.net/json/{0}'.format(ip)) | |
freegeoip_response_json = freegeoip_response.json() | |
user_time_zone = freegeoip_response_json['time_zone'] | |
if user_time_zone: | |
request.session['user_time_zone'] = user_time_zone | |
timezone.activate(pytz.timezone(user_time_zone)) | |
except: | |
pass | |
return None |
Freegeoip provides 10,000 requests per hour by default. So if you need more number of requests, you may have to try some other API.
Now we have implemented middleware to get and activate user timezone in django. Feel free to post your comments.