Date/Time Conversion in Python – ISO 8601 UTC to Pacific Standard Time

I had an issue where I was getting an ISO 8601 UTC date back from one of my API requests and I was asked to convert it to Pacific time as I was providing the information in a report. Since I had no idea what I was doing I first had to figure out what kind of date I was dealing with so that I could then figure out what I was trying to get to.

Here is what an ISO 8601 date looks like:  2019-12-24T15:04:18Z

Here is what the format of the data will look like after the process has been run: 12-24-2019 7:04:18

#Modules needed
import datetime
import pytz

#set the variable for Pacific timezone
pst = pytz.timezone(‘US/Pacific’)

#create the time variable date_time that will be used throughout, the data is coming from an api request and I am getting back json data.
date_time = (ISO 8601 Date)
#set the format for the date time
date_time = datetime.datetime.strptime(date_time, “%Y-%m-%dT%H:%M:%SZ”)
#tell python the current timezone is UTC
date_time = pytz.timezone(‘UTC’).localize(date_time)
#tell python to change the timezone to Pacific
date_time = date_time.astimezone(pst)
#update the variable with the new time and date in the new format
date_time = date_time.strftime(“%m-%d-%y %H:%M:%S”)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.