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
It returns the list and set of commonly used timezones with pytz.
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.
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) .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With