Monday, December 2, 2013

Using time.tzset() in settings.py

I'm looking for the best-practice for handling when a class uses Python's time.timezone and it is imported when the settings file is loaded but it is also instantiated within a Django site. I get the timezone as expected from the OS as opposed to the timezone declared in the TIMEZONE setting because this occur's before django.conf.__init__.py runs time.tzset().

This issue occurs because we're importing:

from celery.schedules import crontab

in our settings file.  We're using celery 3.0.19, so this eventually imports: 

from dateutil import tz


which is the python-dateutil version 2.1 package (http://labix.org/python-dateutil)

(I realize that celery 3.1.x doesn't use dateutil.tz which would solve my problem, but I'm more interested in the most appropriate solution to this issue)

We use the parser class in dateutil.parser.py in our app which uses the tzlocal class in dateutil.tz.py.  This class uses time.timezone when determining the utcoffset for aware datetime objects.  However, as mentioned above, the utcoffset value returns the same value that it would return if run from starting up an interactive interpreter as opposed to what would be returned after performing the timezone reset in django.conf.__init__.py.  This causes datetimes to be off when displayed on our site.

Note that I do not have this issue when running the local development server because of the dual processes running (described in http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html)

My initial solution is to add:

from time import tzset
os.environ['TZ'] = TIME_ZONE
tzset()

to settings.py before dateutil.tz gets imported so that the correct utcoffset is used.  Is this the best solution?

Also, this issue was fairly difficult to track down and demo/explain to others, I'd be willing to add some relevant info to the Django docs concerning this issue if we think that's in store.

Thank you for your time and feedback,
Stephen Christensen

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/c82d56c9-2ea0-4bdf-af27-8faaf71ef637%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment