1

I am new to python. I am confused with importing in python and I am using two python files.

re1.py:

import datetime

import re2

re2.py:

print datetime.datetime.now()

When I run the re1.py file, it gave the error,

print datetime.datetime.now()
NameError: name 'datetime' is not defined

What is the best way to solve this error ?

2 Answers 2

7

When you import datetime in re1.py, you import it in the scope of only the re1.py file, and not in re2.py. In other words, if you import something in one module, it won't cross over onto the other.

To fix this, you must import datetime in re2.py (and you don't necessarily need it in re1.py)

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for reply. datetime is necessary for two files. How to reuse the import modules.
@codeimplementer: The answer is right there. You have to import it in each file where you want to use it.
@codeimplementer I don't know what you mean by re-use, but you can keep the import statement in both files
I mean one file contains all modules and another file import that file. sorry my English is poor.
@codeimplementer Unless you want to do re2.datetime, and the same for every other module, it's better to just import them all in re1.py
0

your code should be:
re1.py:

import datetime  
import re2

re2.py:

import datetime  
print datetime.datetime.now()  

import re2 doesn't means simply replace the statement with another file:

import datetime  
# re2.py  
import datetime  
print datetime.datetime.now()  

you have to make sure all the modules you import are working.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.