Tzach Tzach - 1 year ago 144
Python Question

pytz - Converting UTC and timezone to local time

I have a

in utc time zone, for example:

utc_time = datetime.datetime.utcnow()

And a pytz timezone object:

tz = timezone('America/St_Johns')

What is the proper way to convert
to the given timezone?

Answer Source

I think I got it:

pytz.utc.localize(utc_time, is_dst=None).astimezone(tz)

This line first converts the native utc_time datetime object to a datetime object that contains a timezone (UTC). Then it uses the astimezone function to adjust the time according to the requested time zone.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download