Reputation: 43
I am a beginner with python. In the following code, I imported the "datetime" module and I wanted to get current date and time. But why do I need to write "datetime" twice?
import datetime
now = datetime.datetime.now()
Upvotes: 1
Views: 909
Reputation: 1
import datetime
now = datetime.datetime.now()
Python provides the datetime module to work with real dates and times. From that about code the first datetime
is the module and other datetime
is class and remaining (now
) is the method.
Upvotes: 0
Reputation: 531075
You are importing a module named datetime
.
Due to an unfortunate lack of imagination, one of the classes defined in the datetime
module is also named datetime
. It is that class that defines a class method named now
.
There are other classes defined in the module: datetime.date
, datetime.time
, datetime.timedelta
, etc.
An alternate way of writing this is to import the name of the class directly into the local namespace.
from datetime import datetime
# Now 'datetime' refers to the class, not the module.
now = datetime.now()
Upvotes: 5