python/pytz从本地时区转换为UTC然后返回的问题 [英] Issue with python/pytz Converting from local timezone to UTC then back
本文介绍了python/pytz从本地时区转换为UTC然后返回的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将日期从本地时间戳转换为 UTC,然后再转换回本地时间戳.
I have a requirement to convert a date from a local time stamp to UTC then back to the local time stamp.
奇怪的是,当从 UTC 转换回本地时,python 决定它是 PDT 而不是原始 PST,因此转换后的日期增加了一个小时.有人可以向我解释发生了什么或我做错了什么吗?
Strangely, when converting back to the local from UTC python decides it is PDT instead of the original PST so the post converted date has gained an hour. Can someone explain to me what is going on or what I am doing wrong?
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)
localize
针对夏令时进行调整,replace
不会.有关详细信息,请参阅文档.
localize
adjusts for Daylight Savings Time, replace
does not. See the docs for more info.
这篇关于python/pytz从本地时区转换为UTC然后返回的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文