convert gmt to australian eastern standard time in python

Python has a built-in datetime module which can be used to convert timezones. We can create a datetime object for the GMT time using the datetime.strptime() method and specifying the format of the input time string. We can then use the .replace() method on this datetime object to change the timezone to the Australian Eastern Standard Time (AEST) timezone.

Here is a code snippet demonstrating the conversion:

main.py
from datetime import datetime
import pytz

gmt_time = "2021-08-12 10:00:00"
gmt_format = "%Y-%m-%d %H:%M:%S"

# Create a datetime object for the GMT time
gmt_datetime = datetime.strptime(gmt_time, gmt_format)

# Create timezone objects for GMT and AEST
gmt_timezone = pytz.timezone('GMT')
aest_timezone = pytz.timezone('Australia/Sydney')

# Use the replace method to change the timezone from GMT to AEST
aest_datetime = gmt_timezone.localize(gmt_datetime).astimezone(aest_timezone)

print(aest_datetime.strftime("%Y-%m-%d %H:%M:%S %Z%z"))
540 chars
18 lines

In this code, we first define the input GMT time and its format, then create a datetime object for this time. We then define timezone objects for GMT and AEST using the pytz module. Finally, we use the .replace() method to convert the timezone from GMT to AEST, and print the resulting datetime object in the desired format.

gistlibby LogSnag