Python Dates and Times in Python Where on Earth do Timezones Make Sense? Introduction to Timezones

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?

2 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse 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 Bone
Stephen Bone
12,359 Points

Just 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
Kenneth Love
Treehouse Guest Teacher

I'd probably use a third-party library like pytz or arrow depending on the extent of my needs. If I don't need to deal with timezones, I'd probably just use the built-ins.

Stephen Bone
Stephen Bone
12,359 Points

Hi 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>)