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.
nicole lumpkinCourses 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:
birthday1 datetime.datetime(1984, 8, 29, 0, 0, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>) birthday2 datetime.datetime(1984, 8, 29, 0, 0, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)
What's happening!?! :)
Greg Kaleka39,018 Points
There are two methods, but you've only got one here that will work . 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.
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