pytz - Converting UTC and timezone to local time

2019-02-05 18:38发布

问题:

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?

回答1:

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.



回答2:

May I recommend to use arrow? If I understood the question:

>>> import arrow
>>> utc = arrow.utcnow()
>>> utc
<Arrow [2014-08-12T13:01:28.071624+00:00]>    
>>> local = utc.to("America/St_Johns")
>>> local
<Arrow [2014-08-12T10:31:28.071624-02:30]>

You can also use

tz.fromutc(utc_time)


回答3:

I agree with Tzach's answer. Just wanted to include that the is_dst parameter is not required:

pytz.utc.localize(datetime.utcnow()).astimezone(tz)

That code converts the current UTC time to a timezone aware current datetime.

Whereas the code below converts the current UTC time to a timezone aware datetime which is not necessarily current. The timezone is just appended into the UTC time value.

tz.localize(datetime.utcnow())


回答4:

It's the exact purpose of fromutc function:

tz.fromutc(utc_time)

(as_timezone function calls fromutc under the hood, but tries to convert to UTC first, which is unneeded in your case)



回答5:

Another very easy way:

Because utcnow method returns a naive object, so you have to convert the naive object into aware object. Using replace method you can convert a naive object into aware object. Then you can use the astimezone method to create new datetime object in a different time zone.

from datetime import datetime
import pytz    
utc_time = datetime.utcnow()
tz = pytz.timezone('America/St_Johns')

utc_time =utc_time.replace(tzinfo=pytz.UTC) #replace method      
st_john_time=utc_time.astimezone(tz)        #astimezone method
print(st_john_time)


回答6:

You can also use the sample below, I use it for similar task

tz = pytz.timezone('America/St_Johns')
time_difference=tz.utcoffset(utc_time).total_seconds() #time difference between UTC and local timezones in 5:30:00 format
utc_time = date + timedelta(0,time_difference)

It works fast and you don't need to import additional libraries.