convert chatham time to gmt in python

To convert Chatham time to GMT in Python, you can use the datetime and pytz modules to create timezone-aware datetime objects and convert the timezone accordingly. Here's an example code snippet:

main.py
import datetime
import pytz

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

# create a timezone object for GMT
gmt_tz = pytz.timezone('GMT')

# create a datetime object with Chatham time
chatham_time = datetime.datetime.now(chatham_tz)

# convert Chatham time to GMT time
gmt_time = chatham_time.astimezone(gmt_tz)

# print the output
print("Chatham time:", chatham_time.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
print("GMT time:", gmt_time.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
510 chars
19 lines

In this code, we first create timezone objects for Chatham and GMT using the pytz.timezone() function. Then, we create a datetime object representing the current time in Chatham using the datetime.datetime.now() function, passing in the Chatham timezone object as an argument. Finally, we use the astimezone() method of the datetime object to convert the timezone from Chatham to GMT.

Note that the output format string used with strftime() includes %Z%z to print the timezone name and UTC offset.

gistlibby LogSnag