n0rman0
n0rman0

Reputation: 113

Multiply time in Django TimeField by float

I'm trying to read a time currently represented as a string into a Django TimeField Model in Python 2.7 and scale it via a float at the same time.

For example:

00:31:14 / 1.0617 = 00:29:20

I've successfully read in the time and stored into the model but can't scale the time in a "nice" way (currently I read the time object back out of the database and update it).

I would like to use the python datatime object that the TimeField is based on to do this calculation before saving to the database.

Relevant code:

class Time(models.Model):
    time = models.TimeField()
    date = models.DateField()

date = "12/6/2009"
time = "00:31:14"
date = datetime.strptime(date, "%d/%m/%Y").strftime("%Y-%m-%d")
time = models.Time(date=date, time=time)
time.save()

db_instance = models.Time.objects.all().filter(id=time.id)[0]

db_instance.time = db_instance.time.replace(
    minute=int((db_instance.time.minute * 60 + db_instance.time.second) / 1.0617) / 60,
    second=int((db_instance.time.minute * 60 + db_instance.time.second) / 1.0617) % 60)

Update

As suggested by Dandekar I've extended the timedelta class to include multiplication and division:

from datetime import timedelta

class TimeDeltaExtended(timedelta):
    def __div__(self, divisor):
        return TimeDeltaExtended(seconds=self.total_seconds()/divisor)

    def __mul__(self, multiplier):
        return TimeDeltaExtended(seconds=self.total_seconds()*multiplier)

Upvotes: 2

Views: 624

Answers (1)

AkshayDandekar
AkshayDandekar

Reputation: 435

Division by float does not work in Python 2.x but works in python 3.2x So normally, to SUBTRACT time, you do something like below:

dt = date+" "+time
dt=datetime.datetime.strptime(dt, "%d/%m/%Y %H:%M:%S")
delta=datetime.timedelta(seconds=1.0617)
adjusted=dt-delta
print adjusted.strftime("%d/%m/%Y %H:%M:%S")

To DIVIDE time, you would have to subclass timedelta to something like

class MyTimeDelta(timedelta):
    def __div__(self, deltafloat):
        # Code

More on that here. Hope that helps.

Upvotes: 1

Related Questions