Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put timedelta in django model?

Tags:

django

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...

like image 540
Jack Ha Avatar asked Apr 29 '09 11:04

Jack Ha


People also ask

What is Timedelta in Django?

Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.

What is timestamped model in Django?

TimeStampedModel - An Abstract Base Class model that provides self-managed created and modified fields.

What is duration field in Django?

DurationField is a field for storing periods of time – modeled in Python by timedelta. When used on PostgreSQL, the data type used is an interval and on Oracle the data type is INTERVAL DAY(9) TO SECOND(6). Otherwise, a bigint of microseconds is used.


2 Answers

Since Django 1.8 you can use DurationField.

like image 89
Marc Tudurí Avatar answered Sep 28 '22 09:09

Marc Tudurí


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 ) 
like image 43
S.Lott Avatar answered Sep 28 '22 09:09

S.Lott