Search code examples
pythonpython-3.xpyyaml

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


one of my code lines is

import yaml

which was installed on python 3.7 using pip install pyyaml

the following error arises

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'

How to I get import yaml to work?


Solution

  • You probably have a file called datetime.py in one of the directories shown in the error message (most probably C:/code/EPMD/Kodex/Applications/EPMD-Software/Sandbox/), if you do then you need to rename it to something that will not shadow any other Python module.

    The reasoning is that it masks the actual datetime module, since files/directories/modules in the current working directory have precedence over the modules installed in the site-packages directory (in which the built-in and installed modules live). If both locations contain an a module then import a will import the local a module instead of the (probably) intended a module from site-packages.

    When yaml\representer.py did import datetime it imported your datetime.py file/module which does not have a date attribute, which is why an AttributeError was raised when it later tried to use datetime.date.