Get the time and date in the future with different timezones in python
By Vince
I recently had the need to figure out the date and time in my local timezone (Phoenix) for a future appointment. Bookings on a website don’t open until 12:01AM in their local timezone (HST), so how can you determine what date and time that is locally? Don’t want to be late to book! Counting on the calendar can be wrong by a day as well.
Python to the rescue. Two libraries make this easy: datetime and pytz.
Datetime is built in, but pytz you need to install.
From your command line (if you are not in a virtual environment, this will install globally)
pip3 install pytz
# Now lets open up the python console
python3
# Import our two libraries
from datetime import datetime, timedelta
import pytz
# Create the timezones you need. In this example I am using Hawaii standard time and Phoenix
# You can use either format for the timezone strings (abbreviated or long)
HST = pytz.timezone('HST')
PHX = pytz.timezone('America/Phoenix')
# Create our date (year, month, day, hour, minute, second)
# So Aug 2 2020 at 12:01AM
date = datetime(2020, 8, 2, 0, 1, 00)
# Create the timezone "aware" version of our date
date_HST = HST.localize(date)
# Subtract 90 days from it using the timedelta function. You can also add days, minutes, hours, etc
days_later = date_HST + timedelta(days=-90)
# Create a new date object that has the date in our timezone (PHX)
phx_date = days_later.astimezone(PHX)
# Profit!
print(f"90 days earlier in PHX: {phx_date.strftime(('%Y-%b-%d %H:%M:%S'))}")
90 days earlier in PHX: 2020-May-04 03:01:00
Here is the script version so you can copy/paste easier:
from datetime import datetime, timedelta
import pytz
if __name__ == '__main__':
HST = pytz.timezone('HST')
PHX = pytz.timezone('America/Phoenix')
date = datetime(2020, 8, 2, 0, 1, 00)
date_HST = HST.localize(date)
days_later = date_HST + timedelta(days=-90)
phx_date = days_later.astimezone(PHX)
print(f"time difference: {days_later - date_HST}")