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? 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 68,423 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 68,423 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.