首页 > 解决方案 > AttributeError: type object 'datetime.datetime' 没有属性 'datetime' 即使在使用 import datetime 之后

问题描述

我的烧瓶项目中有以下代码可以修改时间戳。我没有修改任何东西,但是代码现在抛出了上述错误。

我在 StackOverflow 上提到了所有类似的问题,但都表明这是由于使用from datetime import datetime而不是import datetime. 但在我的以下代码中,我使用的是import datetime. 然而,我仍然得到AttributeError: type object 'datetime.datetime' has no attribute 'datetime'.

我的代码:

视图.py

import datetime


@app.template_filter('datetimeformat')
def datetimeformat(value, format):
    d_obj = datetime.datetime.strptime(value, '%Y-%m-%d')
    return d_obj.strftime(format)

@app.template_filter('timestampformat')
def timestampformat(value, format):
    d_obj = datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S') # This is where the error occurs.
    current_date = datetime.date.today()
    timestamp_date = datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S').date()
    if timestamp_date == current_date:
        timestamp_time = datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S').time()
        delta = datetime.timedelta(hours=5, minutes=30)
        timestamp_local = ((datetime.datetime.combine(datetime.date(1,1,1),timestamp_time) + delta).time())
        return "Today at {}".format(timestamp_local.strftime('%I:%M %p'))
    else:
        return d_obj.strftime(format)

模板.html (registration['timestamp'] = 2019-09-13 13:29:47)


...
        <td>{{ registration['timestamp'] }}</td>
        {% if 'Today' in registration['timestamp']|timestampformat('%B %d, %Y %A \n %I:%M %p') %}
            <td><span class="timestamp today">{{ registration['timestamp']|timestampformat('%B %d, %Y, %A, %I:%M %p') }}</span></td>
        {% else %}
            <td><span class="timestamp">{{ registration['timestamp']|timestampformat('%B %d, %Y, %A, %I:%M %p') }}</span></td>
        {% endif %}

...

我真的很困惑出了什么问题。

标签: pythondatetimeflask

解决方案


从 python 文档中,出于效率原因,每个会话只加载一次模块。简单地重新启动解释器(或者在这种情况下,服务器)应该可以解决问题。


推荐阅读