convert gmt to chatham time in python

To convert a datetime object from GMT to Chatham time in Python, you can use the pytz library to create timezone objects for both timezones and then use astimezone() method to convert the datetime object.

Here's an example code snippet that demonstrates how to do this:

main.py
import datetime
import pytz

# create datetime object in GMT timezone
gmt = pytz.timezone('GMT')
dt_gmt = datetime.datetime.utcnow().replace(tzinfo=gmt)

# create timezone object for Chatham
chatham = pytz.timezone('Pacific/Chatham')

# convert the datetime object to Chatham timezone
dt_chatham = dt_gmt.astimezone(chatham)

print('GMT:    ', dt_gmt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
print('Chatham:', dt_chatham.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
452 chars
16 lines

This code will output the current time in both GMT and Chatham timezones:

main.py
GMT:     2021-10-05 09:34:08 GMT+0000
Chatham: 2021-10-05 21:19:08 NZDT+1300
77 chars
3 lines

gistlibby LogSnag