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? 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,018 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: