Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with python/pytz Converting from local timezone to UTC then back

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
like image 376
user578888 Avatar asked Sep 18 '11 23:09

user578888


People also ask

What does pytz timezone return?

It returns the list and set of commonly used timezones with pytz.

How do you convert timezone to UTC in Python?

You can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object.

How do you change timezone from one time zone to another in Python?

Convert to new timezone using . astimezone() on the newly localized datetime/timestamp from step 2 with the desired timezone's pytz object as input e.g. localized_timestamp. astimezone(new_timezone) .


1 Answers

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.

like image 159
unutbu Avatar answered Oct 20 '22 07:10

unutbu