[英]How can I convert from UTC time to local time in python?
So, I want to convert UTC date time 2021-08-05 10:03:24.585Z
to Indian date time how to convert it?那么,我想将 UTC 日期时间
2021-08-05 10:03:24.585Z
转换为印度日期时间如何转换呢?
What I tried is我试过的是
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))
But Still the output is not with the timezone I have mentioned how can I convert the time and print the time from the time.但是 output 仍然不在我提到的时区,我如何转换时间并从时间打印时间。
Output: Output:
2021-08-05 10:03:24.585000+05:21
You can use sth like this:你可以这样使用:
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)
parse the date/time string to UTC datetime correctly and use astimezone instead of replace
to convert to a certain time zone (option for newer Python version (3.9+) in comments):将日期/时间字符串正确解析为 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
If you just need local time, ie your machine's setting, you can use astimezone(None)
as well.如果您只需要本地时间,即您机器的设置,您也可以使用
astimezone(None)
。
In Python 3.10.8在 Python 3.10.8
from datetime import datetime
st = "2021-08-05 10:03:24.585Z"
dtUTC = datetime.fromisoformat(st[:-1]+'+00:00')
dtUTC = dtUTC.astimezone()
print(dtUTC.isoformat(timespec='seconds'))
# 2021-08-05T15:33:24+05:30
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.