This codifies @Sérgio and @unutbu's answers. It will "just work" with either a pytz.timezone
object or an IANA Time Zone string.
def make_tz_aware(dt, tz='UTC', is_dst=None):
"""Add timezone information to a datetime object, only if it is naive."""
tz = dt.tzinfo or tz
try:
tz = pytz.timezone(tz)
except AttributeError:
pass
return tz.localize(dt, is_dst=is_dst)
This seems like what datetime.localize()
(or .inform()
or .awarify()
) should do, accept both strings and timezone objects for the tz argument and default to UTC if no time zone is specified.