[英]Django Template Error: 'unicode' object has no attribute 'year'
我从推特上获取了推文。 在模板推文循环中,我尝试打印此推文创建多久了。 所以这就是我尝试的:
<li class="twitter-feed-block-content">
{{ tweet.text }}
<span class="when">
{{ tweet.created_at|timesince }}
</span>
</li>
{{tweet.text}}
打印正确。 但是,当我添加下一行{{ tweet.created_at|timesince }}
,出现以下错误:
Exception Value: 'unicode' object has no attribute 'year' Exception
Location: REMOVED_BY_ME/lib/python2.7/site-packages/django/utils/timesince.py
in timesince, line 29 Python
Executable: REMOVED_BY_ME/bin/python
Python Version: 2.7.2
tweet.created_at
是一个字符串。 这是原因吗? 如果是这样,我如何转换它,使其与timesince
过滤器无缝timesince
?
提前致谢
使用python strptime将其转换为DateTime对象
datetime_obj = datetime.strptime("2012-10-11", "%Y-%m-%d")
好的,这就是我解决问题的方式。 正如我所说的,我只想创建自定义过滤器作为最后的选择。
因此,我创建了一个名为strtotimesince
的过滤器。 我将其放在此处,以便在有人遇到类似问题时提供帮助。
from django.utils import timesince
@register.filter(name='strtotimesince')
def strtotimesince(value,format=None):
if not value:
return u''
if not format:
format = "%a %b %d %H:%M:%S +0000 %Y"
try:
convert_to_datetime = datetime.strptime(value, format)
if convert_to_datetime:
return "%s ago" % timesince.timesince(convert_to_datetime)
except:
return ''
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.