convert alaska time to gmt in python

main.py
import pytz
from datetime import datetime

# set the timezone
ak_tz = pytz.timezone('America/Anchorage')

# get the current time in Alaska
ak_time = datetime.now(ak_tz)

# convert Alaska time to GMT
gmt_tz = pytz.timezone('GMT')
gmt_time = ak_time.astimezone(gmt_tz)

# format the time to display
gmt_time_str = gmt_time.strftime('%Y-%m-%d %H:%M:%S')

print('Alaska Time:', ak_time.strftime('%Y-%m-%d %H:%M:%S %Z'))
print('GMT Time:', gmt_time_str)
449 chars
19 lines

In this code block, we first import the required modules: pytz and datetime. We then set the timezone to Alaska using pytz.timezone('America/Anchorage').

We get the current time in Alaska using datetime.now(ak_tz).

To convert Alaska time to GMT, we set the timezone to GMT using pytz.timezone('GMT') and use the astimezone() method to convert the Alaska time to GMT.

Finally, we format the time to display using strftime() and print the Alaska and GMT times.

gistlibby LogSnag