我想写一个简单的程序,用Python 3.4打印当前日期。在shell中,我可以导入datetime,并使用now()
,但当我用类编写脚本时,它会失败并给出以下错误:
"AttributeError: module object has no attribute now".
谁能帮我解释一下这个问题?这是我的代码:
import datetime
class Date:
def __init__(self, filename):
self.writeToFile(filename)
def date(self):
now = datetime.datetime.now()
return now
def writeToFile(self, filename):
date = self.date()
file = open(filename, 'w')
file.write(date)
for i in range(20): # simply test for writting in file
file.write(str(i)+'t')
file.close()
return file
d = Date('datetime.txt')
import datetime
datetime.datetime.now()
确保您正在导入预期的datetime模块,并且它没有被同名的本地文件覆盖。你可以用:
import datetime
print(datetime.__file__)
并检查输出是否指向您想要的正确目录。
我也有这个错误,我所做的一切
Import datetime
from datetime import datetime
# then u can declare ur variable let's say something like
today = datetime.datetime.now()
#u can add what ever u want
#the point is make sure u do the datetime.datetime.now()
print(today)