【问题标题】:Issue with python/pytz Converting from local timezone to UTC then backpython / pytz问题从本地时区转换为UTC然后返回
【发布时间】:2011-11-19 21:07:11
【问题描述】:

我需要将日期从本地时间戳转换为 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

【问题讨论】:

    标签: python timezone pytz


    【解决方案1】:

    改变

    date = date.replace(tzinfo=users_timezone)
    

    date = users_timezone.localize(date)
    

    localize 会根据夏令时进行调整,replace 不会。请参阅the docs 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2014-10-05
      • 2012-11-01
      • 2011-09-16
      • 2017-09-27
      • 2012-08-29
      • 2015-06-13
      • 1970-01-01
      • 2017-03-10
      • 2010-11-24
      相关资源
      最近更新 更多