更新时间:2023-11-29 09:46:40
问题是文件是递归导入自身,而不是导入内置模块datetime
:
演示:
$ cat datetime.py导入日期时间打印日期时间.__文件__$ python datetime.py/home/monty/py/datetime.pyc/home/monty/py/datetime.pyc
发生这种情况是因为搜索了模块 按此顺序:
只需将 datetime.py
的名称更改为其他名称即可.
This works in the Python 3.3.2 Shell
>>> import datetime
>>> print(datetime.datetime.utcnow())
2013-07-09 19:40:32.532341
That's great! I then wrote a simple text file named "datetime.py"
#Date time
import datetime
print(datetime.datetime.utcnow())
#Prints GMT, which is named Universal Coordinated Time
# Which is UTC because in French it's something like
# Universahl Tyme Coordinatay
#Outputs something like 2013-07-09 15:15:19.695531
C:\Python33\myscripts>ls
__pycache__ ex1.out ex2.out ex3.py helloworld.py read1.py
datetime.py ex1.py ex2.py first.py pythonintoimportexport.py test.py
Here is where it gets mysterious!
C:\Python33\myscripts>python datetime.py
Traceback (most recent call last):
File "datetime.py", line 2, in <module>
import datetime
File "C:\Python33\myscripts\datetime.py", line 3, in <module>
print(datetime.datetime.utcnow())
AttributeError: 'module' object has no attribute 'utcnow'
Why does the same code work in the Python Shell, but not when run as a script?
The problem is that file is recursively importing itself, instead of importing the built-in module datetime
:
Demo:
$ cat datetime.py
import datetime
print datetime.__file__
$ python datetime.py
/home/monty/py/datetime.pyc
/home/monty/py/datetime.pyc
This happens because the module is searched in this order:
Simply change the name of datetime.py
to something else.