首页 > 解决方案 > Python 将原始 GMT 转换为其他时区,例如 SGT

问题描述

我正在尝试从 GMT 转换为例如 SGT:

例如,值

格林威治标准时间 0348 应该是上午 11:48 格林威治标准时间 1059 应该是下午 6:59

我该怎么做呢?

我努力了:

date="03:48"
curr = (
    dt.datetime.strptime(date, "%H:%M")

    .astimezone(timezone('Asia/Singapore'))
)
print(curr)

但我收到 OSError: [Errno 22] Invalid argument

标签: pythonpython-datetime

解决方案


假设您有一个代表 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)

确保使用replacetzinfo将属性设置为 UTC :

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)

现在您可以使用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'))

旁注,参考您的其他问题,如果您正确解析,您已经获得了一个知道的日期时间对象:

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)

推荐阅读