convert mountain time to gmt in python

To convert a datetime in Mountain Time to GMT (also known as UTC), you can use the pytz library. Here's an example code snippet:

main.py
from datetime import datetime
import pytz

# Create a datetime object in Mountain Time
mt_time = datetime(2021, 10, 20, 16, 30, tzinfo=pytz.timezone('US/Mountain'))

# Convert to GMT/UTC
gmt_time = mt_time.astimezone(pytz.utc)

# Print results
print("Mountain Time:", mt_time)
print("GMT/UTC Time: ", gmt_time)
311 chars
13 lines

In this code, we first create a datetime object representing the Mountain Time we want to convert (in this case, October 20, 2021 at 4:30 PM Mountain Time).

Then, we create a timezone object for Mountain Time with pytz.timezone('US/Mountain'). We use this timezone object as the tzinfo attribute when creating the datetime object.

Next, we use the astimezone() method to convert the datetime object to Greenwich Mean Time (GMT) or Coordinated Universal Time (UTC). We pass in pytz.utc as the timezone object to convert to.

Finally, we print out the original Mountain Time datetime object as well as the converted GMT/UTC datetime object.

gistlibby LogSnag