convert gmt to australian eastern time in python

To convert GMT to Australian Eastern Time (AET) in Python, we need to:

  1. Import necessary modules: datetime, timezone, timedelta, pytz.
  2. Create a datetime object for the GMT time.
  3. Set the UTC timezone for the datetime object.
  4. Convert the timezone to Australian Eastern Time using astimezone method.
  5. Print the converted datetime in AET format.

Here's the Python code to achieve this:

main.py
import datetime
import pytz

# create a datetime object for the GMT time
gmt_datetime = datetime.datetime(2021, 7, 1, 10, 30)

# set the UTC timezone for the datetime object
utc_timezone = pytz.timezone('UTC')
gmt_datetime = utc_timezone.localize(gmt_datetime)

# convert the timezone to Australian Eastern Time
aet_timezone = pytz.timezone('Australia/Sydney')
aet_datetime = gmt_datetime.astimezone(aet_timezone)

# print the converted datetime in AET format
print(aet_datetime.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
515 chars
17 lines

Output:

main.py
2021-07-01 20:30:00 AEST+1000
30 chars
2 lines

gistlibby LogSnag