python/pytz从本地时区转换为UTC然后再转换回UTC的问题

python/pytz从本地时区转换为UTC然后再转换回UTC的问题,python,timezone,pytz,Python,Timezone,Pytz,我需要将日期从本地时间戳转换为UTC,然后再转换回本地时间戳 奇怪的是,当从UTC转换回本地时,python决定它是PDT而不是原始PST,因此转换后的日期增加了一个小时。有人能向我解释一下发生了什么或我做错了什么吗 from datetime import datetime from pytz import timezone import pytz DATE_FORMAT = '%Y-%m-%d %H:%M:%S %Z%z' def print_formatted(dt): for

我需要将日期从本地时间戳转换为UTC,然后再转换回本地时间戳

奇怪的是,当从UTC转换回本地时,python决定它是PDT而不是原始PST,因此转换后的日期增加了一个小时。有人能向我解释一下发生了什么或我做错了什么吗

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)
以下是输出:

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
改变

本地化
调整夏令时,
替换
不调整夏令时。有关更多信息,请参阅

date = date.replace(tzinfo=users_timezone)
date = users_timezone.localize(date)