Aswathy MA
Aswathy MA

Reputation: 43

How to convert local time into GMT time zone in Python

Input:

datetime.now().time()

I need to covert this time into GMT format in python

Can anyone help me for this?

Upvotes: 0

Views: 3116

Answers (1)

FObersteiner
FObersteiner

Reputation: 25634

Assuming by "convert" you mean format to string with a certain suffix.

Option 1: localize to your machine's time zone and strftime:

from datetime import datetime

datetime.now().astimezone(None).strftime("%Y-%m-%d %H:%M:%S GMT%z")
# I'm on CET so this gives me
# '2020-11-30 13:43:15 GMT+0100'

Option 2: localize to specific time zone - and stftime:

# Python 3.9: from zoneinfo import ZoneInfo
from dateutil.tz import gettz # Python <3.9

datetime.now(gettz("Asia/Kolkata")).strftime("%Y-%m-%d %H:%M:%S GMT%z")
# '2020-11-30 18:14:54 GMT+0530'

Upvotes: 0

Related Questions