我在模板中使用{{ prospect.date_1 }} - ({{ prospect.date_1|timesince }} ago)
以获取自该日期起的时间。
关键是,date_1是date
而不是datetime
,所以当我应用过滤器时,它告诉我像
July 18, 2014 - (11 hours, 39 minutes ago)
July 18, 2014 - (0 days ago)
答案 0 :(得分:4)
@register.filter(expects_localtime=True)
def days_since(value, arg=None):
try:
tzinfo = getattr(value, 'tzinfo', None)
value = date(value.year, value.month, value.day)
except AttributeError:
# Passed value wasn't a date object
return value
except ValueError:
# Date arguments out of range
return value
today = datetime.now(tzinfo).date()
delta = value - today
if abs(delta.days) == 1:
day_str = _("day")
else:
day_str = _("days")
if delta.days < 1:
fa_str = _("ago")
else:
fa_str = _("from now")
return "%s %s %s" % (abs(delta.days), day_str, fa_str)
结果
>>> days_since(datetime.now())
'0 days ago'
>>> days_since(date(2013, 5, 12))
'432 days ago'
>>> days_since(date(2014, 12, 12))
'147 days from now'
>>> days_since(date(2014, 7, 19))
'1 day from now'
答案 1 :(得分:0)
@Jack,你有没有尝试使用内置的python:
访问:https://docs.python.org/2/library/datetime.html#datetime.datetime.day
如果这可能会有所帮助:
https://docs.djangoproject.com/en/1.6/ref/contrib/humanize/#naturaltime
from datetime import date
from datetime import datetime
d = date.today()
datetime.combine(d, datetime.min.time())