Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Dates and Times in Python (2014) Where on Earth do Timezones Make Sense? Timezone Strings

Dan Garrison
Dan Garrison
22,457 Points

timezone.py - Why do we need to specifically import timezone from pytz?

I have a quick question about this code challenge. My attached code works, but I don't really understand why. Originally, I only imported the pytz library, but it told me that timezone was not defined. So I tried doing "from pytz import timezone" along with "import pytz". This worked.

Perhaps I'm mistaken, but I was under the impression that when you use from and import together you are only importing the specified method from that library. When you choose to use import without from, you import the entire library with all the methods.

Why do I have to use both in this situation?

timezone.py
import datetime
from pytz import timezone
import pytz

starter = pytz.utc.localize(datetime.datetime(2015, 10, 21, 23, 29))

def to_timezone(tzname):
  return starter.astimezone(timezone(tzname))

2 Answers

If you only import the library as a whole then you need to preface each of that libraries' methods with the library name itself.

i.e.

import pytz

timezone = pytz.timezone
from pytz import timezone

timezone = timezone

So, in theory if you added 'utc' after your timezone import then you could call 'utc' rather than 'pytz.utc' and ditch the 'import pytz' call.

import datetime
from pytz import timezone, utc  #<-----

starter = utc.localize(datetime.datetime(2015, 10, 21, 23, 29))  #<-----

def to_timezone(tzname):
  return starter.astimezone(timezone(tzname))

Yes, that is correct, "from pytz import" = imports specific packages. "import pytz" = imports entire library and sub packages. =D