问题
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 = (
dt.datetime.strptime(date, "%H:%M")
.astimezone(timezone('Asia/Singapore'))
)
print(curr)
But I am getting OSError: [Errno 22] Invalid argument
回答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)
来源:https://stackoverflow.com/questions/63127525/python-convert-raw-gmt-to-othertime-zone-e-g-sgt