PostgreSQL can store data as INTERVAL type, which is close to meaning the same as python's timedelta object (although better in a couple of ways).
I have lots of use for timedelta objects, and having code that basically wrapped integer objects as a number of seconds was common. This module combines the two:
- a timedelta.TimedeltaField() object that transparently converts to and from datetime.timedelta
- storage of the data as an INTERVAL in PostgreSQL, or a string in other databases. (Other databases will be considered if I ever use them, or receive patches).
The coolest part of this package is the way it manipulates strings entered by users, and presents them. Any string of the format:
[X weeks,] [Y days,] [Z hours,] [A minutes,] [B seconds]
will be converted to a timedelta object. Even shortened versions can be used: hrs, hr or h will also suffice. The parsing ignores trailing 's', but is smart about adding them in when presenting the data to the user.
To use, install the package, and use the field:
from django.db import models import timedelta class MyModel(models.Model): the_timedelta = timedelta.TimedeltaField()
There are also some useful methods in helpers.py to work with timedelta objects. (eg, multiply, divide, modulo and percentages).
Additionally, there are two template filters, timedelta and iso8601, which will convert a timedelta object into a valid string.
Parse ISO8601 strings. Thanks to Guillame Libersat, we can generate them.
Handle strings with times in other languages. I'm not really sure about how to do this, but it may be useful.
0.6.3: Correctly parse '1h' as one hour (previously required 1hr).
0.6.2: Remember to include VERSION number.
0.6.0: Added total_seconds helper (for python < 2.7)
0.5.3: Include long_description from this file.
0.5.2: Added decimal_percentage, which gives us a decimal.Decimal object.
0.5.1: Bugfixes from Mike Fogel.
- 0.5: Feature from Guillaume Libersat: helper and template for ISO8601 representation.
- Bugfix from croepha: allow for non-plural 'days' string. Bugfix from Guillaume Libersat: don't explode if initial is None
0.4.7: Bugfix from savemu: use unicode() instead of str()
- 0.4.6: Add in support for PostGIS database.
- Make it easier to add in other column types for other databases.
0.4.5: Restore functionality for django <1.2 (thanks Yoav Aner).
0.4.3: Added helpers.modulo, to allow remainder division of timedlelta objects.
- 0.4.1: changed get_db_prep_value() code to be in get_prep_value(), since I
- was calling it in get_default(), without a connection value.
- 0.4: added the connection and prepared arguments to get_db_prep_value(),
- so that django 1.3+ will not complain of DeprecationWarnings.