Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
why import time 2x
#1
just need a quick explanation on why if i imported time from datetime in line 2, do i need to import again in line 3 to make this work?

ctime wont appear if i dont import time on its own line... as a newbie, just a little confused


import datetime
from datetime import date, time, timedelta
import time

mtime= path.getmtime('textfile.txt')
t = time.ctime((mtime) )
print(t)
Reply
#2
actually, these are different
on line 2 you import datetime.time
while on line 3 you import time module

now, on line 1 you import datetime module as a whole, then on line 2 you import some of the available objects in the same module. i.e. if we talk of duplicate imports, it's line 1 and line 2
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
thanks, now line 3 makes sense, its actually a different library

so once you import the library (import datetime) you dont need to import the individual objects? (im i wording this correctly?) why do i see this so much in tutorials?
Reply
#4
(Apr-16-2019, 06:09 PM)ilcaa72 Wrote: so once you import the library (import datetime) you dont need to import the individual objects? (im i wording this correctly?) why do i see this so much in tutorials?
it depends. with the datetime module probably most/many would prefer to import the individual objects they would use. The difference is how you would reference them
python3.7

compare
Python 3.7.3 (default, Mar 26 2019, 01:59:45) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2019, 4, 16, 21, 20, 40, 991213)
>>> datetime.date.today()
datetime.date(2019, 4, 16)
and

Python 3.7.3 (default, Mar 26 2019, 01:59:45) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime, date
>>> datetime.now()
datetime.datetime(2019, 4, 16, 21, 22, 31, 802438)
>>> date.today()
datetime.date(2019, 4, 16)
>>> 
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
You can type just the imported module name into the console.
You get back the representation of the object. This works with all objects.
In addition you can import inspect and get the sourcefile of a loaded module.

Here some examples:
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020