32
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 )
- [Django]-Django: how do I query based on GenericForeignKey's fields?
- [Django]-Authenticate by IP address in Django
- [Django]-Django: guidelines for speeding up template rendering performance
8
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.
- [Django]-How can I resolve 'django_content_type already exists'?
- [Django]-Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4
- [Django]-Editing django-rest-framework serializer object before save
- [Django]-Django: show/log ORM sql calls from python shell
- [Django]-Has Django served an excess of 100k daily visits?
- [Django]-Django-debug-toolbar not showing up
4
There is a ticket which dates back to July 2006 relating to this:
https://code.djangoproject.com/ticket/2443
Several patches were written but the one that was turned in to a project:
https://github.com/johnpaulett/django-durationfield
Compared to all the other answers here this project is mature and would have been merged to core except that its inclusion is currently considered to be “bloaty”.
Personally, I’ve just tried a bunch of solutions and this is the one that works beautifully.
from django.db import models
from durationfield.db.models.fields.duration import DurationField
class Event(models.Model):
start = models.DateTimeField()
duration = DurationField()
@property
def finish(self):
return self.start + self.duration
Result:
$ evt = Event.objects.create(start=datetime.datetime.now(), duration='1 week')
$ evt.finish
Out[]: datetime.datetime(2013, 6, 13, 5, 29, 29, 404753)
And in admin:
Change event
Duration: 7 days, 0:00:00
- [Django]-Paginating the results of a Django forms POST request
- [Django]-Create Django model or update if exists
- [Django]-Django filter many-to-many with contains
3
For PostgreSQL, use django-pgsql-interval-field here: http://code.google.com/p/django-pgsql-interval-field/
- [Django]-Mac OS X – EnvironmentError: mysql_config not found
- [Django]-How do I use django rest framework to send a file in response?
- [Django]-Django: Set foreign key using integer?
2
Putting this out there cause it might be another way to solve this problem.
first install this library: https://pypi.python.org/pypi/django-timedeltafield
Then:
import timedelta
class ModelWithTimeDelta(models.Model):
timedeltafield = timedelta.fields.TimedeltaField()
within the admin you will be asked to enter data into the field with the following format: 3 days, 4 hours, 2 minutes
- [Django]-AbstractUser vs AbstractBaseUser in Django?
- [Django]-Django development server reload takes too long
- [Django]-Django datetime issues (default=datetime.now())
0
There is a workaround explained here. If you’re using Postgresql, then multiplying the result of F
expression with timedelta
solves the problem. For example if you have a start_time
and a duration
in minutes, you can calculate the end_time
like this:
YourModel.objects.annotate(
end_time=ExpressionWrapper(F('start_time') + timedelta(minutes=1) * F('duration'), output_field=DateTimeField())
)
- [Django]-Django admin default filter
- [Django]-Django error: got multiple values for keyword argument
- [Django]-How do I convert datetime.timedelta to minutes, hours in Python?