When do we need `from` and `import` vs just `import`?

Modules Exercises 1
import sentence is

from datetime import datetime

Okay, I see.

But Exercises 2

import random

Why is there no from word?
What is the differences between them?

The datetime module gives you access to several classes, among them date, time and datetime.

If you want to make use of the datetime class of the datetime module (yes, it’s confusing: same name for two different things), you have two choices:
(1) Import the module and prefix the class with datetime using dot notation:

import datetime
d = datetime.datetime(2000, 12, 31)  # This is a datetime object; note the dot notation
print(d)
# Prints 
2000-12-31 00:00:00

or…
(2) Use from to import the class and then just use the class name, omitting the dot notation:

from datetime import datetime
e = datetime(2000, 12, 31)   # no dot notation needed to create a datetime object
print(e)
# Prints 
2000-12-31 00:00:00

The same relation holds with modules and functions which they may contain:

import random
p = random.randint(0, 10)   # this is a function accessed via dot notation
print(p)   

# or

from random import randint
q = randint(0, 10)   # no dot notation needed for this function
print(q)    

# Prints
6
2

(Edited to correct a mistake in the final example.)

25 Likes

I see. Thank you for your clear explanation.
I really appreciate you.

6 Likes

a= randint(0,100)
is randint a class or a method inside a class?

Is it possible to import more than just one class from a module?

Yes we can import multiple objects or classes at once

from math import log,pi,ceil,floor

print(pi,log(32,2),ceil(3.2),floor(3.2))

Output:

3.141592653589793 5 4 3

It appears to be a method of the “random” class. See https://docs.python.org/3/library/random.html for reference.