如何在 django 模板中减去两个 datetime.time 值,以及如何将持续时间格式化为小时、分钟

2024-03-04

在 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

你有问题了。你不能——也不应该能够——比较两次。晚上11点是凌晨1点之前还是之后?这取决于他们是否在同一天。

您需要将它们存储为datetime或者其他代表相对绝对时间的东西,或者你需要把它们变成datetime像这样:

def todatetime(time):
    return datetime.datetime.today().replace(hour=time.hour, minute=time.minute, second=time.second, 
                                             microsecond=time.microsecond, tzinfo=time.tzinfo)

def timestodelta(starttime, endtime):
    return todatetime(endtime) - todatetime(starttime)

如果这两个调用都无法给出预期的答案today跨越午夜。

那么您可能应该使用这个应用程序持续时间字段 http://django-durationfield.readthedocs.org/en/latest/其中存储了一个timedelta将结果存储在数据库中以便于显示。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 django 模板中减去两个 datetime.time 值,以及如何将持续时间格式化为小时、分钟 的相关文章

随机推荐