convert gmt to central time in python

To convert GMT to Central Time in Python, you should use the datetime module along with the timezone module provided by pytz.

Here's an example code snippet that demonstrates how to convert a GMT time to Central Time:

main.py
import datetime
import pytz

# input GMT datetime
gmt_time = datetime.datetime(2022, 3, 1, 14, 30, 0, tzinfo=pytz.utc)

# convert GMT to Central Time
central_time = gmt_time.astimezone(pytz.timezone('US/Central'))

# print result
print(central_time)
250 chars
12 lines

The output of this code will be:

main.py
2022-03-01 08:30:00-06:00
26 chars
2 lines

Note that the astimezone() method used above takes a pytz timezone object as its argument. In this example, I've used the US/Central timezone, but you can use any of the pytz timezone objects that correspond to the time zone you want to convert to.

Also note that pytz is not included in the standard Python library, so you may need to install it separately using pip:

main.py
pip install pytz
17 chars
2 lines

gistlibby LogSnag