Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytz - Converting UTC and timezone to local time

I have a datetime 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 utc_time to the given timezone?

like image 788
Tzach Avatar asked Aug 12 '14 12:08

Tzach


People also ask

How do you convert UTC time to local time?

Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.). Note The date also follows UTC format.

What is pytz UTC?

The pytz package encourages using UTC for internal timezone representation by including a special UTC implementation based on the standard Python reference implementation in the Python documentation. The UTC timezone unpickles to be the same instance, and pickles to a smaller size than other pytz tzinfo instances.

How do you convert UTC to local time zone in Python?

This datetime object will have no timezone associated with it. Therefore assign the UTC timezone to this datetime object using replace(tzinfo=pytz. UTC) function. Convert the timezone of the datetime object to local timezone by calling the astimezone() function on datetime object.


1 Answers

I think I got it:

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

This line first converts the naive (time zone unaware) 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.

like image 69
Tzach Avatar answered Sep 25 '22 08:09

Tzach