Time Zone Utilities for Django Models
django-timezone-utils adds automatic time zone conversions and support utilities to Django.
Suggestions, constructive criticism, and feedback are certainly welcomed and appreciated.
Documentation for django-timezone-utils is available at Read the Docs.
On multiple occasions, I have had the need to store time zone information to the one model, then base another model’s datetime on that time zone. If you have ever had to deal with this, you will know how complicated this can be.
I created these fields to ease the process of manipulating times based on another field’s or models timezone choice. Instead of having to remember to use Model.clean, we can now create the models with the validation built into the model field.
from datetime import datetime from timezone_utils.fields import LinkedTZDateTimeField, TimeZoneField from timezone_utils.choices import PRETTY_ALL_TIMEZONES_CHOICES class Location(models.Model): # ... timezone = TimeZoneField(choices=PRETTY_ALL_TIMEZONES_CHOICES) def get_location_timezone(obj): """Returns the Location.timezone field from above""" return obj.location.timezone class LocationReport(models.Model): # ... location = models.ForeignKey('app_label.Location', related_name='reports') # Populates from the Location.timezone timestamp = LinkedTZDateTimeField(populate_from=get_location_timezone) class LocationPeriod(models.Model): # ... location = models.ForeignKey('app_label.Location', related_name='periods') # Sets the time to 12:00am in the location.timezone start = LinkedTZDateTimeField( populate_from=get_location_timezone, time_override=datetime.min.time() ) # Sets the time to 11:59:59.99999pm in the location.timezone end = LinkedTZDateTimeField( populate_from=get_location_timezone, time_override=datetime.max.time() )