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? Timezonapalooza

Why can't we localize directly against the UTC timezone

I see the following in the code presented in the video:

local_date = pytz.timezone('US/Pacific').localize(local_date)
utc_date = local_date.astimezone(pytz.utc)

Since pytz.utc is a timezone why can't we just do the following:

utc_date = pytz.utc.localize(local_date)

I see no reason to go through the 'US/Pacific' timezone first before shifting to UTC. Am I missing something?

Ok, I think I got this...

At first, local_date is naive so it has absolutely no location info attached to it. I first need to tag it with my current location which I know based on the reality of where my computer is currently situated. My computer does not know where it is located and I have to tell it explicitly. Only after I have my hands on a datetime object which knows something about the current location I can shift it to another timezone (in this case UTC).

5 Answers

William Gough
William Gough
18,852 Points

I've just passed this challenge after reviewing the video and workspace. The following should pass.

import datetime

import pytz

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

def to_timezone(zone):
  local = pytz.timezone(zone)
  return starter.astimezone(local)

Hope this helps anybody who is struggling. I'm assuming you could also do it in one line:

return starter.astimezone(pytz.timezone(zone))

Let me know if this works for you!

The python from the video is the universal way it is guaranteed to work. The second example will only work given if the program is running from the correct geographic location. =)

Alex Khimchak
Alex Khimchak
4,876 Points

very confused datetime course.

John Barge
John Barge
4,807 Points

If I'm not mistaken, this code assumes that the user inputting the time is using the program in the pacific timezone. That is the only reason to localize the naive datetime input to the US/Pacific timezone. The code then derives a matching time in the UTC timezone for use in the rest of the code. Please correct me if I'm wrong.

Did I give best answer? =D