Issue with python/pytz Converting from local timez

2020-07-10 05:25发布

问题:

I have a requirement to convert a date from a local time stamp to UTC then back to the local time stamp.

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)

And here is the output:

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:

Change

date = date.replace(tzinfo=users_timezone)

to

date = users_timezone.localize(date)

localize adjusts for Daylight Savings Time, replace does not. See the docs for more info.