Python: datetime tzinfo time zone names documentation

The standard library does not define any timezones — at least not well (the toy example given in the documentation does not handle subtle problems like the ones mentioned here). For predefined timezones, use the third-party pytz module.

import pytz
import datetime as DT

eastern = pytz.timezone('US/Eastern')
utc = pytz.utc
test="2013-03-27 23:05"

This is a “naive” datetime:

test2 = DT.datetime.strptime(test, '%Y-%m-%d %H:%M')   
print(test2)
# 2013-03-27 23:05:00

This makes a timezone-aware datetime by interpreting test2 as if it were in the EST timezone:

print(eastern.localize(test2))
# 2013-03-27 23:05:00-04:00

This makes a timezone-aware datetime by interpreting test2 as if it were in the UTC timezone:

print(utc.localize(test2))
# 2013-03-27 23:05:00+00:00

Alternatively, you can convert one timezone-aware datetime to another timezone using the astimezone method:

test2_eastern = eastern.localize(test2)
print(test2_eastern.astimezone(utc))
# 2013-03-28 03:05:00+00:00

Leave a Comment