Python convert raw GMT to othertime zone e.g SGT

别说谁变了你拦得住时间么 提交于 2021-02-11 12:22:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!