shortest Python timezones example

assuming we import datetime and pytz, just for a little bit of brevity ….

print datetime.datetime.utcnow().replace(tzinfo=pytz.utc).\
   astimezone(pytz.timezone("US/Eastern")).strftime("%Y-%m-%d %H:%M")

Whoa Nelly, Break it down bro! Below is an example of getting a ‘Naive’ time. I.E. it will be the time of the computer you are using, but have no associated timezone designation. This example also will get an error if you can’t import datetime.

import datetime
nowVariable =
print nowVariable

But a naive time object is unaware of the timezone, and the pytz object library is a great addition to datetime, but again, the next example will make your time object timezone aware, but first it will test that your computer can import the pytz object library.

import datetime, pytz
nowVariable =
laTimeVariable = nowVariable.replace(tzinfo=pytz.timezone("US/Pacific"))
print laTimeVariable

Other timezones could be US/Mountain, US/Central, Europe/Rome, Australia/Perth, Asia/Hong_Kong, etc.

Now, if we want to print the ‘aware’ date object in a pretty format, we can say;

print laTimeVariable.strftime("%Y-%m-%d %H:%M %Z")

This is great to populate the display variable when the date and time are sent to the screen. But with many different timezones and everything happening on the world wide dub dub dub all over the world at all hours, internally to my python code, I might want to always store and calculate the time in one single standard timezone, only converting as the last step to display it to a local user.

To get the current universal time, naive and aware;

utcNaiveVariable = datetime.datetime.utcnow()
utcAwareVariable = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)