How to put timedelta in django model?

Since Django 1.8 you can use DurationField.


You can trivially normalize a timedelta to a single floating-point number in days or seconds.

Here's the "Normalize to Days" version.

float(timedelta.days) + float(timedelta.seconds) / float(86400)

You can trivially turn a floating-point number into a timedelta.

>>> datetime.timedelta(2.5)
datetime.timedelta(2, 43200)

So, store your timedelta as a float.

Here's the "Normalize to Seconds" version.

timedelta.days*86400+timedelta.seconds

Here's the reverse (using seconds)

datetime.timedelta( someSeconds/86400 )

https://bitbucket.org/schinckel/django-timedelta-field/src


First, define your model:

class TimeModel(models.Model):
    time = models.FloatField()

To store a timedelta object:

# td is a timedelta object
TimeModel.objects.create(time=td.total_seconds())

To get the timedelta object out of the database:

# Assume the previously created TimeModel object has an id of 1
td = timedelta(seconds=TimeModel.objects.get(id=1).time)

Note: I'm using Python 2.7 for this example.