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.
datetime.timezone python 2.7 attribute error
Does datetime.timezone work with 2.7? I can utilize it in Workspaces, but I believe Workspaces is running a newer version?
I see there is something called 'pytz' (https://pypi.python.org/pypi/pytz/). Is this the best solution?
Kenneth LoveTreehouse Guest Teacher
You want to avoid working with pure
datetime.timezone() as much as possible, regardless of Python version. Not because it's bad, it does what it says, but because it's too much to look up and remember and remember to change if/when the timezones shift again.
Stephen Bone12,359 Points
No it looks like the datetime.timezone class was added into Python 3 at some point.
I haven't used it before so can't say it is exactly the same as using datetime.timezone in Python 3 (perhaps someone else can weigh in on that) but using pytz certainly looks favourable rather than trying to implement an instance of tzinfo in 2.7.
I've played around with it and worked through the example that Kenneth uses and it appears to return the same result.
The code I used is below. Hope it helps!
>>> import datetime, pytz >>> pacific = pytz.timezone('US/Pacific') >>> eastern = pytz.timezone('US/Eastern') >>> aware = pacific.localize(datetime.datetime(2014, 4, 21, 9)) >>> aware datetime.datetime(2014, 4, 21, 9, 0, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>) >>> aware.astimezone(eastern) datetime.datetime(2014, 4, 21, 12, 0, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)