Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

146
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda