将Django TimeField中的时间乘以float [英] Multiply time in Django TimeField by float
问题描述
我正在尝试将当前表示为字符串的时间读入Python 2.7的Django TimeField模型中,并同时通过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.
例如:
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).
在保存到数据库之前,我想使用TimeField所基于的python datatime对象进行此计算.
I would like to use the python datatime object that the TimeField is based on to do this calculation before saving to the database.
相关代码:
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)
更新
如Dandekar所建议,我将timedelta类扩展为包括乘法和除法:
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)
推荐答案
按浮点数除法在Python 2.x中不起作用,但在python 3.2x中起作用因此,通常来说,要减去时间,您需要执行以下操作:
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")
要划分时间,您必须将timedelta子类化为类似的
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.
这篇关于将Django TimeField中的时间乘以float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!