Python __import__() function

As we write python programs we need various other modules to leverage their functions, classes etc. in our current program. We can import those modules at the runtime using the import function. Though you can also import named modules at the beginning of the code, you may need the module temporarily for only few lines of code or you want to make the copy of an object from the module and modify and use it.


The syntax of the __import__() function is −

__import__(name, globals=None, locals=None, fromlist=(), level=0)
name - the name of the module you want to import
globals and locals - determines how to interpret name
fromlist - objects or submodules that should be imported by name
level - specifies whether to use absolute or relative imports

In the below example we import the DateTime module and dcreate custom objects with values as needed in the program.


 Live Demo

dttime = __import__('datetime', globals(), locals(), [], 0)
# Make a copy of dttime
x =
# Get your custom results


Running the above code gives us the following result −

2021-01-12 07:38:54.903330

The use of __import__ is discouraged and you can import the entire module at the beginning of the code for greater efficiency.