convert new zealand time to gmt in python

To convert New Zealand Time (NZT) to GMT (Greenwich Mean Time) in Python, you can use the pytz module to work with time zones and the datetime module to handle dates.

Here is an example code snippet to convert a given datetime object from NZT to GMT:

main.py
import pytz
from datetime import datetime

# create a datetime object representing a certain date and time
dt = datetime(2021, 8, 31, 19, 30, 0)

# create timezone objects for NZT and GMT
nzt = pytz.timezone('Pacific/Auckland')
gmt = pytz.timezone('GMT')

# localize the datetime object to the NZT timezone
nzt_dt = nzt.localize(dt)

# convert to the GMT timezone and remove timezone information
gmt_dt = nzt_dt.astimezone(gmt).replace(tzinfo=None)

print(gmt_dt)  # output: 2021-08-31 07:30:00
495 chars
18 lines

In this example, we first create a datetime object dt representing a specific date and time in NZT. Then, we create timezone objects for NZT and GMT using the pytz.timezone() function. We localize the dt object to NZT using the .localize() method of the NZT timezone object.

Finally, we convert the localized datetime object to the GMT timezone using the .astimezone() method of the NZT datetime object, and remove the timezone information using the .replace(tzinfo=None) method of the GMT datetime object. The resulting datetime object gmt_dt represents the same date and time in GMT, which is printed to the console.

gistlibby LogSnag