Skip to content Skip to sidebar Skip to footer

Python Convert Raw Gmt To Othertime Zone E.g Sgt

I am trying to convert from GMT to e.g SGT: For example, the value 0348 GMT should be 11:48 am 1059 GMT should be 6:59 pm how do i do this? i have tried: date='03:48' curr = (

Solution 1:

Assuming you have a naive datetime object which represents UTC:

from datetime import datetime, timezone
from dateutil import tz

now = datetime.now()
print(repr(now))
>>> datetime.datetime(2020, 7, 28, 8, 5, 42, 553781)

Make sure to set the tzinfo property to UTC using replace:

now_utc_aware = now.replace(tzinfo=timezone.utc)
print(repr(now_utc_aware))
>>> datetime.datetime(2020, 7, 28, 8, 5, 42, 553781, tzinfo=datetime.timezone.utc)

Now you can convert to another timezone using astimezone:

now_sgt = now_utc_aware.astimezone(tz.gettz('Asia/Singapore'))
print(repr(now_sgt))
>>> datetime.datetime(2020, 7, 28, 16, 5, 42, 553781, tzinfo=tzfile('Singapore'))

Sidenote, referring to your other question, if you parse correctly, you already get an aware datetime object:

date = "2020-07-27T16:38:20Z"
dtobj = datetime.fromisoformat(date.replace('Z', '+00:00'))
print(repr(dtobj))
>>> datetime.datetime(2020, 7, 27, 16, 38, 20, tzinfo=datetime.timezone.utc)

Post a Comment for "Python Convert Raw Gmt To Othertime Zone E.g Sgt"