调用函数时发生AttributeError

时间:2018-06-22 11:58:00

标签: python

我试图根据时间显示一些消息,但是在尝试调用该函数时出现以下错误。

Traceback (most recent call last):
  File "autodrive.py", line 31, in <module>
    goodbye()
  File "autodrive.py", line 19, in goodbye
    now = datetime.now()
AttributeError: 'module' object has no attribute 'now'

import datetime
import random
import re 
import sys

def goodbye():
    now = datetime.now()
    now_time = now.time()

    bye = ['byee', 'see u', 'see you', 'au revoir']
    night = ['goodnight', 'gn', 'bye', 'sleep well', 'bonne nuit']

    if now_time >= time(21,30) or now_time <= time(4,00):
        print random.choice(night)

    if now_time >= time(4,00) or now_time <= time(21,30):
        print random.choice(bye)

goodbye()

4 个答案:

答案 0 :(得分:2)

您导入了模块datetime。该模块包含一个类,也称为datetime,该类具有名为now的类方法。您需要引用整个内容:

now = datetime.datetime.now()

答案 1 :(得分:1)

写:

from datetime import datetime

更新(完整代码):

from datetime import datetime
import datetime as dt
import random
import re
import sys

def goodbye():
    now = datetime.now()
    now_time = now.time()

    bye = ['byee', 'see u', 'see you', 'au revoir']
    night = ['goodnight', 'gn', 'bye', 'sleep well', 'bonne nuit']

    if now_time >= dt.time(21,30) or now_time <= dt.time(4,0):
        print( random.choice(night))

    if now_time >= dt.time(4,0) or now_time <= dt.time(21,30):
        print(random.choice(bye))

goodbye()

答案 2 :(得分:1)

请使用其中任何一个

import datetime
dt= datetime.datetime.now()


from datetime import datetime
dt= datetime.now()

答案 3 :(得分:0)

now = datetime.datetime.now()

代替

now = datetime.now()