Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda