import datetime from django.db import models from django.db.backends.mysql.base import django_conversions from django.conf import settings from MySQLdb.constants import FIELD_TYPE django_conversions.update({FIELD_TYPE.TIME: None}) SECONDS_PER_MIN = 60 SECONDS_PER_HOUR = SECONDS_PER_MIN * 60 SECONDS_PER_DAY = SECONDS_PER_HOUR * 24 class TimeAsTimeDeltaField(models.Field): """ Custom field for mapping TIME columns to timedelta values, not times, so that we can store values greater than 24 hours. See ticket #354 and http://docs.djangoproject.com/en/1.0/howto/custom-model-fields/#howto-custom-model-fields """ __metaclass__ = models.SubfieldBase def db_type(self): return 'time' def to_python(self, value): if value is None: return None if isinstance(value, datetime.timedelta): return value hours, minutes, seconds = map(int, value.split(':')) total_seconds = seconds + (60 * (minutes + (60 * hours))) result = datetime.timedelta(seconds=total_seconds) return result def get_db_prep_value(self, value): if not value: return None total_seconds = value.seconds + (value.days * SECONDS_PER_DAY) return '%02i:%02i:%02i' % ( total_seconds / SECONDS_PER_HOUR, # hours total_seconds / SECONDS_PER_MIN - total_seconds / SECONDS_PER_HOUR * 60, # minutes - Total seconds subtract the used hours total_seconds % SECONDS_PER_MIN # seconds )