【问题标题】:django personal filter datetimedjango个人过滤器日期时间
【发布时间】:2015-10-18 04:44:29
【问题描述】:

我想找出某个日期与 15 天后的日期之间的天数。 我创建了一个个人过滤器:

register = template.Library()

import datetime

@register.filter
def nbDays(thedate):
    res = 0
    passed = datetime.datetime.now() - thedate
    res = 15 - passed   
return res

我有这个错误:

can't subtract offset-naive and offset-aware datetimes

当我调用方法时:

{% load nameOfFile %}

{{ objectGood.created_at|nbDays }}

【问题讨论】:

  • 你的设置中有USE_TZ = True吗?
  • 不,我搜索如何使用它
  • 是真的:我有这个 USE_I18N = True USE_L10N = True USE_TZ = True

标签: python django django-templates django-filter django-template-filters


【解决方案1】:

如果您在设置中启用了时区,那么您需要让您的所有 datetime 对象知道时区。

Django 让这很容易;

register = template.Library()

from django.utils import timezone

@register.filter
def nbDays(thedate):
    res = 0
    passed = timezone.now() - thedate
    res = 15 - passed   
return res

或者,您可以从日期时间对象中删除时区感知;

timezone_unaware_date = thedate.replace(tzinfo=None)

【讨论】:

  • 它不起作用,我有这个错误:不支持的操作数类型为 -: 'int' 和 'datetime.timedelta'。但我找到了一个解决方案: now = datetime.datetime.utcnow().replace(tzinfo=utc) 但我完全不知道。谢谢
  • 你正在做15 - passed 其中passed 是一个日期时间对象hense 类型错误。如果您想开始从日期时间对象中添加/减去天数等,您需要查看 relativedeltalabix.org/…
猜你喜欢
  • 2016-07-21
  • 2016-07-20
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
  • 2014-03-31
  • 2023-03-23
  • 1970-01-01
  • 2021-03-05
相关资源
最近更新 更多