将日期和时间从 UTC 转换为指定格式的本地
Convert date and time from UTC to local in specifed format
我的 UTC 日期时间为 2021-02-24 12:41:40
。
我想将其转换为 24 小时格式的本地时区,即相同格式的“IST”,即 2021-02-24 18:11:40
。
我在 Whosebug 上参考了很多答案,但我无法获得所需格式的结果。
如何在Python3中实现?
我链接的内容特别适用于您的问题:
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 tzinfo to 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
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(' ')
我的 UTC 日期时间为 2021-02-24 12:41:40
。
我想将其转换为 24 小时格式的本地时区,即相同格式的“IST”,即 2021-02-24 18:11:40
。
我在 Whosebug 上参考了很多答案,但我无法获得所需格式的结果。
如何在Python3中实现?
我链接的内容特别适用于您的问题:
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 tzinfo to 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
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(' ')