If you are going to store it as a datetime (which I agree is a good idea), I would extend DateTimeProperty - then you will get free bits of analysis and verification.
Also, saving as a timedelta as a datetime can be much easier than the other methods given here by storing it as a datetime at some distance from the referenced datetime, so the difference is timedelta. This is really easy because the operator overloads the datetime module.
from datetime import datetime, timedelta from google.appengine.ext import db class TimeDeltaProperty(db.DateTimeProperty):
And here is the equivalent implementation for the NDB API , if you are so inclined:
from datetime import datetime, timedelta from google.appengine.ext import ndb class TimeDeltaProperty(ndb.DateTimeProperty): # Use a reference datetime half way between the min and max possible # datetimes, so that we can support both +ve and -ve timedeltas ref_datetime = (datetime.max - datetime.min) / 2 + datetime.min def _validate(self, value): if not isinstance(value, timedelta): raise TypeError('expected a datetime.timedelta, got %r' % value) def _to_base_type(self, value): # datetime + timedelta = datetime return self.ref_datetime + td def _from_base_type(self, value): # datetime - datetime = timedelta return dt - self.ref_datetime
Accuracy
A timedelta in Python can handle a delta of about +/- 2.7 million years. However, datetime only covers about 10,000 years. To save a large timedelta in datetime, you will need to shift a little and sacrifice some accuracy.
The above approach limits half of this range to about +/- 5000 years due to the choice of reference time and time.
If you know that timedelta will always be positive, you can use ref_datetime = datetime.min (or if you know that always will be negative, you can use ref_datetime = datetime.max ) to get the full range of about 10,000 years.