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

John Schut
John Schut
2,317 Points

Challenge Task timezone.py

What is wrong with my code?

Return(starter) didn't work either...

timezone.py
import datetime

import pytz

def to_timezone(timezone_string):
    starter = pytz.utc.localize(datetime.datetime(2015, 10, 21, 23, 29))
    starter = starter.astimezone(tz=pytz.timezone(timezone_string))
    starter_string = starter.strftime('%y-%m-%d %H:%M')
    starter_datetime = datetime.datetime.strptime(starter_string, '%y-%m-%d %H:%M')
    return(starter_datetime)

to_timezone('Europe/Amsterdam')

2 Answers

John Schut
John Schut
2,317 Points

Hi Steven,

Thanks! I was close enough to justify this 'Spoiler Alert'... :-)

Steven Parker
Steven Parker
231,269 Points

Looks like you're overthinking this one. You nearly had it with just one of your lines. Here's some hints:

  • There's a function that converts a localized time to another zone, using a timezone object.
  • There's another function that converts a string into a timezone object.
  • If you combine these functions, you can get the converted time with a one-liner
  • starter is defined for you as a global variable, you won't need to define it inside your function
  • For the challenge, you only define your to_timezione function, you don't call it yourself

Can you do it now with just the hints?


If not...


:warning: SPOILER ALERT


def to_timezone(timezone_string):
    return starter.astimezone(pytz.timezone(timezone_string))