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

I can't really get why we need to turn an aware datetime to UTC before start to convert the datetime to other timezones.

If I have an aware datetime, when we use .astimezone() on it, it will automatically turn it into whatever other timezone I want it to.

But here in Kenneth's script:

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

        output = []
        for timezone in OTHER_TIMEZONES:
            output.append(utc_date.astimezone(timezone))
        for appointment in output:
            print(appointment.strftime(fmt))
        break

Why do I have this utc_date variable? Couldn't I just write less code that works the same like this:

else:
        local_date = pytz.timezone('US/Pacific').localize(local_date)
        # Deleted utc_datetime
        output = []
        for timezone in OTHER_TIMEZONES:
            output.append(local_date.astimezone(timezone)) # Used local_date instead of utc_date
        for appointment in output:
            print(appointment.strftime(fmt))
        break

I saw Kenneth explaining that we convert datetimes to UTC because UTC doesn't deal with daylight savings time, but I still can't understand what it has to do with anything.

2 Answers

Steven Parker
Steven Parker
231,269 Points

Perhaps the idea was to practice converting to and from a storage format. It is considered "best practice" to store dates and times as UTC to simplify portability. Even though nothing gets stored in this particular example it may be to demonstrate the concept.

I'd agree with @steven here. It is not strictly necessary to get a UTC-localized datetime before converting timezones, but, since UTC is the default standard timezone, it is good practice to normalise your data to UTC before doing any conversions.