AttributeError: module 'datetime' has no attribute 'date' on import yaml

AttributeError: module 'datetime' has no attribute 'date' on import yaml

我的代码行之一是

import yaml

使用 pip install pyyaml

安装在 python 3.7 上

出现如下错误

Traceback (most recent call last):

File "C:/code/EPMD/Kodex/Applications/EPMD-Software/Sandbox/peer_changing_send_rate.py", line 1, in from TestPeer.TestPeerChangingSendRate import TestPeerChangingSendSpeed File "C:\code\EPMD\Kodex\Applications\EPMD-Software\TestPeer\TestPeerChangingSendRate.py",

line 1, in from .TestPeer import TestPeer File "C:\code\EPMD\Kodex\Applications\EPMD-Software\TestPeer\TestPeer.py",

line 4, in from BaseProcess.ZmqPeerClass import ZmqPeer File "C:\code\EPMD\Kodex\Applications\EPMD-Software\BaseProcess\ZmqPeerClass.py",

line 2, in from .ZmqPublisherClass import ZmqPublisher File "C:\code\EPMD\Kodex\Applications\EPMD-Software\BaseProcess\ZmqPublisherClass.py",

line 10, in from . import ZmqProcessClass File "C:\code\EPMD\Kodex\Applications\EPMD-Software\BaseProcess\ZmqProcessClass.py",

line 5, in from .ConfigBaseClass import ConfigBase File "C:\code\EPMD\Kodex\Applications\EPMD-Software\BaseProcess\ConfigBaseClass.py",

line 3, in import yaml File "C:\code\EPMD\Kodex\venv\lib\site-packages\yaml__init__.py", line 9, in from .dumper import * File "C:\code\EPMD\Kodex\venv\lib\site-packages\yaml\dumper.py", line 6, in from .representer import * File "C:\code\EPMD\Kodex\venv\lib\site-packages\yaml\representer.py", line

263, in SafeRepresenter.add_representer(datetime.date, AttributeError: module 'datetime' has no attribute 'date'

如何让 import yaml 工作?

您可能在错误消息中显示的目录之一中有一个名为 datetime.py 的文件(很可能是 C:/code/EPMD/Kodex/Applications/EPMD-Software/Sandbox/),如果您这样做,则需要将其重命名为不会隐藏任何其他 Python 模块。

原因是它屏蔽了实际的 datetime 模块,因为当前工作目录中的 files/directories/modules 优先于安装在 site-packages 目录中的模块(其中内置-in 和已安装的模块)。如果两个位置都包含 a 模块,那么 import a 将导入本地 a 模块,而不是来自 site-packages.[=25 的(可能)预期的 a 模块=]

yaml\representer.py 做了 import datetime 它导入了你的 datetime.py file/module 没有 date 属性,这就是为什么 AttributeError 后来尝试使用 datetime.date.

时引发