Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
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)
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!