2011-09-18 10 views
7

Ho un obbligo di convertire una data da un timestamp locale a UTC e di nuovo al timestamp locale.Problema con python/pytz Conversione da fuso orario locale a UTC, quindi ritorno

Stranamente, quando si converte di nuovo in locale da UTC python decide che è PDT anziché PST originale, quindi la data di conversione post ha guadagnato un'ora. Qualcuno può spiegarmi cosa sta succedendo o cosa sto facendo male?

from datetime import datetime 
from pytz import timezone 
import pytz 

DATE_FORMAT = '%Y-%m-%d %H:%M:%S %Z%z' 

def print_formatted(dt): 
    formatted_date = dt.strftime(DATE_FORMAT) 
    print "%s :: %s" % (dt.tzinfo, formatted_date) 


#convert the strings to date/time 
date = datetime.now() 
print_formatted(date) 

#get the user's timezone from the pofile table 
users_timezone = timezone("US/Pacific") 

#set the parsed date's timezone 
date = date.replace(tzinfo=users_timezone) 
date = date.astimezone(users_timezone) 
print_formatted(date) 

#Create a UTC timezone 
utc_timezone = timezone('UTC') 
date = date.astimezone(utc_timezone) 
print_formatted(date) 

#Convert it back to the user's local timezone 
date = date.astimezone(users_timezone) 
print_formatted(date) 

Ed ecco l'output:

None :: 2011-09-18 18:24:23 
US/Pacific :: 2011-09-18 18:24:23 PST-0800 
UTC :: 2011-09-19 02:24:23 UTC+0000 
US/Pacific :: 2011-09-18 19:24:23 PDT-0700 

risposta

6

Change

date = date.replace(tzinfo=users_timezone) 

a

date = users_timezone.localize(date) 

localize regola per l'ora legale, replace fa n ot. Vedi the docs per maggiori informazioni.

+0

Grazie. – user578888

Problemi correlati