【问题标题】:Python convert raw GMT to othertime zone e.g SGTPython将原始GMT转换为其他时区,例如SGT
【发布时间】:2020-07-28 05:25:04
【问题描述】:

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

例如值

0348 GMT 应该是上午 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

【问题讨论】:

标签: python python-datetime


【解决方案1】:

假设您有一个代表 UTC 的 naive datetime object:

from datetime import datetime, timezone
from dateutil import tz

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

确保使用replace 将tzinfo 属性设置为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'))

旁注,参考your other question,如果你解析正确,你已经得到了一个有意识的日期时间对象:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 2014-08-25
    相关资源
    最近更新 更多