views:

977

answers:

3

With inspectdb I was able to get a "interval" field from postgres into django. In Django, it was a TextField. The object that I retrieved was indeed a timedelta object!

Now I want to put this timedelta object in a new model. What's the best way to do this? Because putting a timedelta in a TextField results in the str version of the object...

+1  A: 

This link may be helpfull: Timedelta Snippets

Andrea Di Persio
+3  A: 

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

Here's the "Normalize to Days" version.

timedelta.days+timedelta.seconds/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 )
S.Lott
off course you mean float(timedelta.days) + float(timedelta.seconds)/float(86400) ... but it works!
Jack Ha
@Jack Ha: Thanks for spotting the problem.
S.Lott
timedelta.days+timedelta.seconds/86400.0
Wahnfrieden
+1  A: 

For PostgreSQL, use django-pgsql-interval-field here: http://code.google.com/p/django-pgsql-interval-field/

dotz