在 django 应用程序中,我发送了一个列表Entry
对象到模板。每个Entry
对象有一个开始时间和结束时间,它们是 datetime.time 值(从TimeFields
在表单上)。在列出条目对象时,我需要显示每个条目的持续时间。在模型中放置持续时间字段似乎是多余的,因为开始和结束时间已经存在
model
class Entry(models.Model):
title = models.CharField(unique=True,max_length=50)
starttime=models.TimeField(null=True)
endtime=models.TimeField(null=True)
...
template
{% for entry in object_list %}
<tr>
<td> {{entry.title}} </td>
<td> {{entry.starttime}}</td>
<td> {{entry.endtime}}</td>
<td> want to show duration here </td>
{%endfor %}
1.
是否有任何过滤器可以采用两个 datetime.time 值并计算以秒为单位的持续时间。
IE,
given
t1=datetime.time(2,30,50) and
t2=datetime.time(3,00,50)
should show
30 minutes
2.
另外,是否有一个过滤器,可以将给定分钟数的持续时间显示为小时,分钟(如果分钟值大于 60)
ie,
if duration is 50 minutes ==> 50 minutes
if duration is 150 minutes ==> 2 hours,30 minutes
update
def diff_in_time(start,end):
startdelta=datetime.timedelta(hours=start.hour,minutes=start.minute,seconds=start.second)
enddelta=datetime.timedelta(hours=end.hour,minutes=end.minute,seconds=end.second)
return (enddelta-startdelta).seconds/60
当我尝试使用一些样本时间值时,它给了我预期的结果
#start 11:35:00 pm
#end 00:05:00 am
start= datetime.time(23,35,00)
end = datetime.time(00,05,00)
print diff_in_time(start,end)
==> 30 minutes
#start 00:35:00 am
#end 01:35:00 am
start= datetime.time(00,35,00)
end = datetime.time(01,35,00)
print diff_in_time(start,end)
==>60 minutes