简体   繁体   中英

Parse an UTC time, and render it as a local-timezone time

I have a string named utctime which is a date/time in UTC timezone:

import time
utctime = "2017-01-12 08:38:28"      # UTC
t = time.strptime(utctime, "%Y-%m-%d %H:%M:%S")

How to render this date/time as local-server-timezone? This:

time.strftime("%Y-%m-%d %H:%M:%S", t)
# "2017-01-12 08:38:28"

doesn't work obviously because I get the UTC time again.

Is it possible with just time or datetime module and nothing else?

PS: I'm myself in UTC+1.

If you wanted to stick with just time or datetime, you would have to implement your own timezones (D:). Here is a way to do it using pytz.

from datetime import datetime
import pytz    
utc_time = datetime.utcnow()
tz = pytz.timezone('US/Pacific')

utc_time =utc_time.replace(tzinfo=pytz.UTC)   
pst_time=utc_time.astimezone(tz)
print pst_time

More information on the library is here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM