user3085639
user3085639

Reputation: 3

Why is this first line of code important in Python?

I am currently using Codeacademy to learn Python. It is the first language I have ever tried to learn and I am currently stuck. Now I'm not stuck because I couldn't get past a certain lesson. I'm stuck because I had to do a quick search on the internet to find out what the first line of code was supposed to be. It never said anything about that first line anywhere and I want to know what it's supposed to do. Here is the full code when it is completed, correctly:

from datetime import datetime
now = datetime.now()
print now
year = now.year
month = now.month
day = now.day
print year
print month
print day
print str(month) + "/" + str(day) + "/" + str(year)

I kept getting an error telling me that datetime is not defined. I finally found that first line by looking through the Q&A section of Codeacademy.

Upvotes: 0

Views: 204

Answers (2)

jfs
jfs

Reputation: 414179

It is an issue with Codeacademy environment. It may be restricted for educational purposes. The import should work in an ordinary Python environment:

from datetime import datetime # import `datetime` class from `datetime` module

print(datetime.utcnow()) # call class method

datetime is a stdlib module. It is always available.

It can also could be written as:

import datetime # import module

print(datetime.datetime.utcnow()) # module.klass.klassmethod()

Rule of thumb for a well-written Python code: unless it is a builtin function or a Python keyword then you could find where any name that is used in the code were introduced just by looking at the source code.

Module names are introduced using import statements at the top of the file with the source code usually.

Make sure there is no datetime.py file in your current working directory if you are trying this code on your local computer. Otherwise import statement will use it instead of the one from stdlib.

Upvotes: 1

Lenny
Lenny

Reputation: 5939

That first line defines datetime (hence the error). More specifically, it imports the datetime object from the datetime module.

More info here: http://effbot.org/zone/import-confusion.htm

Upvotes: 0

Related Questions