1 votes

ImportError: cannot import name 'date' from partially initialized module 'datetime'

For example I write the following code:

from datetime import date, time

print("fecha actual: ", date.today()) 

I get as a result:

ImportError: cannot import name 'date' from partially initialized module 'datetime' (most likely due to a circular import)

2 votes

It works for me. There must be something else, did you post the full code?

2 votes

It may also be because there is a file with the name datetime.py


As Leonardo indicates in the comments what is happening is that you have named within the same file a file (possibly the same one you are in) with the name datetime.py . This is why you get the error:

ImportError: cannot import name 'date' from partially initialized module 'datetime' (most likely due to a circular import)

This is due to the fact that Python, when importing, looks for the module to import in the following way.

  1. First look for the module in the cache, to see if it has already been imported. If it has already been imported, it fetches it from the cache. We can see what Python has in the cache with sys.modules
  2. Second will sys.path and search for the module, if the module is found there import it (this is your case). If it is not found it gives an import error.

Now let's go to your case, which is the second one :

If we execute:

import sys


This gives us all the paths where Python looks for your modules, Always the first path will be the directory where the file you are executing is located. . It will never be the place where you have the packages installed. So if in the directory where you are running your program you have a file with the name of a package, will try to import that file, instead of the module that is installed. . And this is where your mistake comes from.

If you want to know more about importing libraries, you can see this other question from the site How to import libraries in a fast and optimized way in Python?

1 votes

In fact, now the module import is somewhat more sophisticated, with a pre-fetching of module loaders in sys.meta_path . It may even be that the module does not exist as a file or that it is part of a zip file. The correct thing to do would be to use importlib.util.find_spec to find out where a module comes from.

0 votes

Thank you very much @ChemaCortes for the information, I will read well the documentation and as soon as I can I will improve the answer :)


HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by: