convert pacific time to eastern time in python

To convert Pacific Time to Eastern Time in Python, you can make use of the datetime library and the pytz library which provides timezone support. Here is an example code snippet:

main.py
import datetime
import pytz

pacific = pytz.timezone('US/Pacific')
eastern = pytz.timezone('US/Eastern')

pacific_time = datetime.datetime.now(pacific) # Replace "now" with your desired Pacific Time datetime object

eastern_time = pacific_time.astimezone(eastern)

print("Pacific Time: ", pacific_time.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
print("Eastern Time: ", eastern_time.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
411 chars
13 lines

Explanation of the code:

  • We first import the necessary libraries - datetime and pytz.
  • We then create timezone objects for Pacific Time and Eastern Time using the pytz.timezone() method.
  • We create a datetime object for the desired Pacific Time using datetime.datetime.now(). You can also create a datetime object for a specific time or date using datetime.datetime(year, month, day, hour, minute, second, tzinfo=pacific).
  • We then use the .astimezone() method to convert the Pacific Time datetime to Eastern Time.
  • Finally, we print the Pacific and Eastern Time in the desired format using the .strftime() method.

gistlibby LogSnag