【问题标题】:Find the difference between two Django datetimes找出两个 Django 日期时间之间的差异
【发布时间】:2015-04-15 06:47:50
【问题描述】:

我有一个模板标签如下,

     @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

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

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

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

【问题讨论】:

  • value 的类型是什么?是模型吗,date_startdate_end 是 DateTimeField?
  • 该代码无法给出该错误。尽管您的 if 逻辑中有错误(应该是 if date_start is not None and date_end is not None),但如果其中之一是 None,您仍然不会收到该错误 - 您会收到“TypeError: must be str, not None”。
  • @sneawo:是的,它在数据库表中的日期时间

标签: django datetime templatetag


【解决方案1】:

如果value 是模型,date_startdate_end 是 DateTimeFields,那么向模型中添加方法会更容易

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

并在模板中使用它:

{{ value.runtime }}

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

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

在模板中:

{% get_runtime value.date_start value.date_end %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 2021-12-24
    • 2023-03-24
    • 2012-09-13
    相关资源
    最近更新 更多