转换本地时区到UTC再转回来的Python/pytz问题

7
我有一个需求,需要将本地时间戳转换为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
1个回答

6

更改

date = date.replace(tzinfo=users_timezone)

to

date = users_timezone.localize(date)

localize 方法可以调整夏令时,但 replace 不能。请参阅文档了解更多信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接