找出两个Django日期时间之间的区别

时间:2021-06-18 21:27:59

I have a template tag as follows,

我有一个模板标签如下,

     @register.filter
def get_runtime(date_start=None, date_end=None):
    fmt = '%Y-%m-%dT%H:%M:%S'
    if date_start and date_end is not None:
        date_start = datetime.strptime(date_start, fmt)
        date_end = datetime.strptime(date_end, fmt)
        return date_end - date_start
    else:
        return None

and I am passing it into one of my website as follows,

我将它传递到我的网站之一,如下所示,

<b>Run Time (min): </b> {{ value.date_start|get_runtime:value.date_end }}<br>

But it showing an error "strptime() takes exactly 2 arguments (1 given)" Please help me on this. Thanks in advance

但它显示错误“strptime()需要2个参数(给出1个)”请帮我解决这个问题。提前致谢

1 个解决方案

#1


0  

If value is a model and date_start, date_end are DateTimeFields, then it's easier to add a method to model

如果value是model和date_start,date_end是DateTimeFields,那么更容易将方法添加到模型中

def runtime(self):
    if self.date_start and self.date_end:
        return self.date_end - self.date_start

and use it in template:

并在模板中使用它:

{{ value.runtime }}

For your solution it's better use a tag instead of filter, because you do not modify value and calculate something else. Function returns None by default. So it will look like:

对于您的解决方案,最好使用标记而不是过滤器,因为您不会修改值并计算其他内容。函数默认返回None。所以它看起来像:

@register.simple_tag
def get_runtime(date_start, date_end):
    if date_start and date_end:
        return date_end - date_start

in template:

{% get_runtime value.date_start value.date_end %}

#1


0  

If value is a model and date_start, date_end are DateTimeFields, then it's easier to add a method to model

如果value是model和date_start,date_end是DateTimeFields,那么更容易将方法添加到模型中

def runtime(self):
    if self.date_start and self.date_end:
        return self.date_end - self.date_start

and use it in template:

并在模板中使用它:

{{ value.runtime }}

For your solution it's better use a tag instead of filter, because you do not modify value and calculate something else. Function returns None by default. So it will look like:

对于您的解决方案,最好使用标记而不是过滤器,因为您不会修改值并计算其他内容。函数默认返回None。所以它看起来像:

@register.simple_tag
def get_runtime(date_start, date_end):
    if date_start and date_end:
        return date_end - date_start

in template:

{% get_runtime value.date_start value.date_end %}