如何将 python 中的 UTC 时间转换为本地时间?

How can I convert from UTC time to local time in python?

所以,我想将 UTC 日期时间 2021-08-05 10:03:24.585Z 转换为印度日期时间,如何转换?

我试过的是

from datetime import datetime

from pytz import timezone

st = "2021-08-05 10:03:24.585Z"

datetime_object = datetime.strptime(st, '%Y-%m-%d %H:%M:%S.%fZ')

local_tz = timezone('Asia/Kolkata')
start_date = local_tz.localize(datetime_object)
print(start_date.replace(tzinfo=local_tz))

但输出仍然不符合我提到的时区,我该如何转换时间并打印时间。

输出:

2021-08-05 10:03:24.585000+05:21

将 date/time 字符串正确解析为 UTC 日期时间并使用 astimezone 而不是 replace 转换为特定时区(选项对于较新的 Python 版本(3.9+)在评论中:

from datetime import datetime
# from zoneinfo import ZoneInfo
from dateutil.tz import gettz

st = "2021-08-05 10:03:24.585Z"
zone = "Asia/Kolkata"

# dtUTC = datetime.fromisoformat(st.replace('Z', '+00:00'))
dtUTC = datetime.strptime(st, '%Y-%m-%d %H:%M:%S.%f%z')

# dtZone = dtUTC.astimezone(ZoneInfo(zone))
dtZone = dtUTC.astimezone(gettz(zone))

print(dtZone.isoformat(timespec='seconds'))
# 2021-08-05T15:33:24+05:30

如果您只需要当地时间,即您机器的设置,您也可以使用 astimezone(None)

你可以这样使用:

from datetime import datetime
from dateutil import tz

from_zone = tz.gettz('UTC')
to_zone = tz.gettz('Asia/Kolkata')

utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')

utc = utc.replace(tzinfo=from_zone)

central = utc.astimezone(to_zone)

对于Python 3.7+

from datetime import datetime
st = "2021-08-05 10:03:24.585Z"
dtUTC = datetime.fromisoformat(st[:-1])
dtZone = dtUTC.astimezone()
print(dtZone.isoformat(timespec='seconds'))
# 2021-08-05T15:33:24+05:30