convert eastern time to gmt in python

To convert Eastern Time to GMT in Python, you can use the datetime module and the timezone class. Follow the steps below:

  1. Import the datetime module
  2. Create a datetime object representing the Eastern Time with the timezone set to 'US/Eastern'
  3. Convert the Eastern Time datetime object to UTC/GMT by calling the astimezone() method and passing 'UTC' as the timezone argument
  4. Format the resulting datetime object as a string in the desired format using the strftime() method

Here's the code:

main.py
import datetime
from pytz import timezone

# create a datetime object representing Eastern time
eastern = datetime.datetime.now(timezone('US/Eastern'))

# convert Eastern time to UTC
utc = eastern.astimezone(timezone('UTC'))

# format UTC datetime object as a string
utc_string = utc.strftime('%Y-%m-%d %H:%M:%S')

print(utc_string)
333 chars
14 lines

This will output the current date and time in GMT/UTC time zone.

gistlibby LogSnag