Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Dates and Times in Python Where on Earth do Timezones Make Sense? pytz Format

Loh Pin Hua
Loh Pin Hua
3,160 Points

It just doesn't make sense!

I just can't seem to pass this challenge. Can you help me?

pytzstring.py
import datetime

fmt = '%m-%d %H:%M %Z%z'
starter = datetime.datetime(2015, 10, 21, 4, 29)
def to_timezone(new_timezone):
  # generate timezone from string
  new_tz = pytz.timezone(new_timezone) 
  # convert starter to new datetime
  new_dt = starter.astimezone(new_tz) 
  # Return new datetime object
  local = new_dt
  return local
Chris Freeman
Chris Freeman
Treehouse Moderator 67,986 Points

You should not create a function for this challenge.

Loh Pin Hua
Loh Pin Hua
3,160 Points

Just give me the answer.

3 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 67,986 Points

For Task 1 you need:

import datetime
import pytz

fmt = '%m-%d %H:%M %Z%z'
starter = datetime.datetime(2015, 10, 21, 4, 29)

pacific = pytz.timezone('US/Pacific')
local = pacific.localize(starter)

Loh Pin Hua could you specify a little bit, what you don't get?

Did you already read the docs? https://pythonhosted.org//pytz/

I don't think you can use astimezone on a naive datetime. Instead, use localize on a pytz timezone object and pass the naive datetime to it.

You might also need to import pytz first.

From the pytz docs:

from datetime import datetime, timedelta
>>> from pytz import timezone
>>> import pytz
...
>>> eastern = timezone('US/Eastern')
...
>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))
>>> print(loc_dt.strftime(fmt))
2002-10-27 06:00:00 EST-0500
Loh Pin Hua
Loh Pin Hua
3,160 Points

I still don't get it.