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

use*_*888 7 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):
    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)
Run Code Online (Sandbox Code Playgroud)

这是输出:

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
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 6

更改

date = date.replace(tzinfo=users_timezone)
Run Code Online (Sandbox Code Playgroud)

date = users_timezone.localize(date)
Run Code Online (Sandbox Code Playgroud)

localize调整夏令时,replace不会.有关详细信息,请参阅文档.