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? Actually, Use pytz Instead

nicole lumpkin
nicole lumpkin
Courses Plus Student 5,328 Points

Two ways of creating an aware datetime obj, what's the difference?

It seems like you can create an aware datetime object in two ways.

By specifying the tzinfo:

import datetime
import pytz

eastern = pytz.timezone('US/Eastern')
birthday1 = datetime.datetime(1984, 8, 29, tzinfo = eastern)

And by using .localize()

birthday2 = eastern.localize(datetime.datetime(1984, 8, 29))

However when I looked at birthday1 and birthday2, there were subtle differences:

datetime.datetime(1984, 8, 29, 0, 0, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>)

datetime.datetime(1984, 8, 29, 0, 0, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)

What's happening!?! :)

1 Answer

Greg Kaleka
Greg Kaleka
39,021 Points

Hi Nicole,

There are two methods, but you've only got one here that will work :blush:. The problem is that using the first method doesn't work with timezones that use daylight savings time. Notice that your two birthday variables have "STD" and "DST" at the end. The .localize() version correctly set dst = True.

From the pytz docs:

This library only supports two ways of building a localized time. The first is to use the localize() method provided by the pytz library. This is used to localize a naive datetime (datetime with no timezone information):

>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))

The second way of building a localized time is by converting an existing localized time using the standard astimezone() method:

>>> ams_dt = loc_dt.astimezone(amsterdam)

Unfortunately using the tzinfo argument of the standard datetime constructors β€˜β€™does not work’’ with pytz for many timezones ... It is safe for timezones without daylight saving transitions though, such as UTC.

Hope that helps - have fun with datetimes :smile:

Cheers :beers: