convert gmt to samoa time in python

To convert GMT to Samoa time in Python, you can use the datetime module along with the pytz library to handle timezones.

First, you need to create a datetime object representing the time in GMT. You can do this with the datetime.utcnow() function, which returns the current UTC time.

main.py
import datetime

gmt_time = datetime.datetime.utcnow()
print("GMT Time:", gmt_time)
84 chars
5 lines

Output:

main.py
GMT Time: 2021-09-16 04:12:35.123456
37 chars
2 lines

Next, you need to create a timezone object representing the Samoa timezone. You can do this with the pytz.timezone() function, passing in the timezone identifier Pacific/Apia.

main.py
import pytz

samoa_tz = pytz.timezone("Pacific/Apia")
54 chars
4 lines

Finally, you can convert the GMT time to Samoa time by using the astimezone() method of the datetime object and passing in the Samoa timezone object.

main.py
samoa_time = gmt_time.astimezone(samoa_tz)
print("Samoa Time:", samoa_time)
76 chars
3 lines

Output:

main.py
Samoa Time: 2021-09-16 05:12:35.123456+14:00
45 chars
2 lines

The output shows the Samoa time, which is one hour ahead of GMT (as Samoa is at UTC+14).

So, the complete code to convert GMT to Samoa time in Python is:

main.py
import datetime
import pytz

gmt_time = datetime.datetime.utcnow()
samoa_tz = pytz.timezone("Pacific/Apia")
samoa_time = gmt_time.astimezone(samoa_tz)

print("GMT Time:", gmt_time)
print("Samoa Time:", samoa_time)
214 chars
10 lines

gistlibby LogSnag