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? 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
221,328 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))