2011-09-18 11 views
7

Tengo un requisito para convertir una fecha de una marca de tiempo local a UTC y luego volver a la marca de hora local.Problema con python/pytz Convirtiendo de la zona horaria local a UTC y luego a

Curiosamente, al convertir de nuevo al local de UTC, python decide que es PDT en lugar del PST original, por lo que la fecha de conversión posterior ha ganado una hora. ¿Puede alguien explicarme qué está pasando o qué estoy haciendo mal?

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) 

Y aquí está la salida:

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 

Respuesta

6

Cambio

date = date.replace(tzinfo=users_timezone) 

a

date = users_timezone.localize(date) 

localize ajusta al horario de verano, hace replace n Antiguo Testamento. Consulte the docs para obtener más información.

+0

Gracias que lo arregló. – user578888

Cuestiones relacionadas