- Intro: My project
TIME_ZONEis equal to'UTC'while I have users from too many time zones. So, when I user makePOSTorPUTwithdateortimeordateTimefields I convert these fields toUTCbeforeserializer.save(). Then, when a user make aGETrequest I convert the same fields back to the timezone of the user which isrequest.user.timezone
# simplified functions
def localize(usertimzone, date, type):
"""
type = 'date', 'time', 'datetime'
"""
from dateutil import parser
date = parser.parse(date)
if not date.tzinfo:
usertimzone = pytz.timezone(usertimzone)
date = usertimzone.localize(date)
utc_date = date.astimezone(pytz.utc)
return utc_date
def normalize(usertimzone, date, type):
current_user_tz = pytz.timezone(usertimzone)
date = current_user_tz.localize(date)
return date
#usages example
def post(self, request, *args, **kwargs):
alert_date = request.data.get('alert_date')
if alert_date:
request.data['alert_date'] = localize(request.user.timezone, alert_date, 'datetime')
- Problem: I used these function in too many views and every time I create a new view I use it again.
- Goal: I need to find a way to do that in one function that generalize this conversion for all
dateField,timeFieldanddatetimeFieldfields. - I tried: to make a class view and use these functions inside it then override that class for each new app. But, each model have date fields with different names and it was hard to make a flexible function that recognize which field need to be localized or normalized.
Note: I mean by normalized to convert the timezone from UTC the the current login-in user timezone.