Python 中的 ISO 时间与人类可读时间

cod*_*uff 4 python datetime strftime epoch strptime

我正在使用Python。我的时间格式是这样的

2020-05-23T06:35:11.418279Z #May 23, 2020 at 12:05:11 PM GMT+05:30
Run Code Online (Sandbox Code Playgroud)

我想转换成人类可读的时间,比如

23-05-2020 12:05 PM
Run Code Online (Sandbox Code Playgroud)

我也尝试过解析器。但没有效果。

谁能帮我这个?

提前致谢 :)

MrF*_*pes 5

另请参阅如何解析 ISO 8601 格式的日期?

不幸的是fromisoformat由于Z. 您可以改用strptime解决方法或 dateutil 的解析器。前任:

from datetime import datetime
import dateutil

s = '2020-05-23T06:35:11.418279Z'

### parsing options
# strptime
dt = datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f%z')
# alternatively fromisoformat with replace (most efficient)
dt = datetime.fromisoformat(s.replace('Z', '+00:00'))
# or more convenient and a bit less efficient:
dt = dateutil.parser.isoparse(s)

# change timezone to Indian Standard Time:
dt = dt.astimezone(dateutil.tz.gettz('Asia/Kolkata'))
# datetime.datetime(2020, 5, 23, 12, 5, 11, 418279, tzinfo=tzfile('Asia/Calcutta'))

# note for Python 3.9+:
# use zoneinfo from the standard lib to get timezone objects

# now format to string with desired format
s_out = dt.strftime('%Y-%m-%d %I:%M %p')
s_out
# '2020-05-23 12:05 PM' 
Run Code Online (Sandbox Code Playgroud)