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 trialcassac
9,628 Pointsdatetime.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?
2 Answers
Kenneth Love
Treehouse Guest TeacherYou 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 Bone
12,359 PointsHi Chad
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!
Stephen
>>> 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>)
Stephen Bone
12,359 PointsStephen Bone
12,359 PointsJust wondering how you would normally handle it for a project then. Would you use pytz (or another library) instead or do you just avoid it altogether where possible and use it reluctantly when you have to?
Kenneth Love
Treehouse Guest TeacherKenneth Love
Treehouse Guest TeacherI'd probably use a third-party library like
pytz
orarrow
depending on the extent of my needs. If I don't need to deal with timezones, I'd probably just use the built-ins.