简体   繁体   English

以指定格式将日期和时间从 UTC 转换为本地

[英]Convert date and time from UTC to local in specifed format

I have UTC date time as 2021-02-24 12:41:40 .我的 UTC 日期时间为2021-02-24 12:41:40

I want to get it converted into local timezone in 24 hour format ie "IST" in same format ie 2021-02-24 18:11:40 .我想将其转换为 24 小时格式的本地时区,即相同格式的“IST”,即2021-02-24 18:11:40

I referred many answers on Stackoverflow, but I am not able to get the result in desired format.我在 Stackoverflow 上引用了许多答案,但我无法以所需的格式获得结果。

How can it be achieved in Python3?在Python3中如何实现?

what I linked applied specifically to your question:我链接的内容专门适用于您的问题:

from datetime import datetime, timezone
from dateutil.tz import gettz

# the given info:
ist = gettz("Asia/Kolkata")
s = "2021-02-24 12:41:40"

# now parse to datetime and set time zone UTC
dt = datetime.fromisoformat(s).replace(tzinfo=timezone.utc)

# convert to IST time zone
dt = dt.astimezone(ist)

# output to isoformat string, but without time zone info
s = dt.replace(tzinfo=None).isoformat(' ')

print(s)
# 2021-02-24 18:11:40

Solution for Python 3.6.* Python 3.6.* 的解决方案

        datetime = "2021-02-24 12:41:40"
        from_zone = tz.tzutc()
        to_zone = tz.tzlocal()
        utc = datetime.strptime( datetime,'%Y-%m-%d %H:%M:%S')
        utc = utc.replace(tzinfo=from_zone)
        local = utc.astimezone(to_zone)
        localTime = local.replace(tzinfo=None).isoformat(' ')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM