convert gmt to new zealand time in python

To convert GMT to New Zealand Time in Python, use the pytz library and its timezone functionality. Here's an example code snippet:

main.py
import datetime
import pytz

# create a datetime object for a specific GMT time
gmt_time = datetime.datetime(2022, 6, 1, 12, 0, 0, tzinfo=pytz.timezone('GMT'))

# convert the GMT time to New Zealand time
nz_time = gmt_time.astimezone(pytz.timezone('Pacific/Auckland'))

# format the New Zealand time as a string
nz_time_str = nz_time.strftime('%Y-%m-%d %H:%M:%S %Z%z')

print(nz_time_str) # output: '2022-06-02 00:00:00 NZST+1200'
431 chars
14 lines

In this example, we first create a datetime object for a specific GMT time by specifying the year, month, day, hour, minute, and second, and including the tzinfo parameter to indicate the timezone as pytz.timezone('GMT').

We then use the astimezone() method to convert this GMT time to the New Zealand timezone, specified as pytz.timezone('Pacific/Auckland').

Finally, we format the New Zealand time as a string using the strftime() method with the desired format ('%Y-%m-%d %H:%M:%S %Z%z'), and print the result.

Note that the strftime() method also allows for various other formatting options, such as displaying the time in a different time zone or using a different date/time format.

gistlibby LogSnag