Python 如何将日期时间文本转换为日期时间对象?

How to convert a datetime text into datetime object in Python?

我想将 datetime 字符串转换为 datetime 对象,该对象将进一步处理以不同的格式显示。

字符串在for中,2018-04-24T16:42:17Z

我试过下面的方法,但是报错。

import datetime
datetime.datetime.strptime('2018-04-24T16:42:17Z', '%b %d %Y %I:%M%p')


Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\Python\lib\_strptime.py", line 510, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "D:\Python\lib\_strptime.py", line 343, in _strptime
    (data_string, format))
ValueError: time data '2018-04-24T16:42:17Z' does not match format '%b %d %Y %I:%M%p'

请帮忙。

您的日期时间字符串表示有些不匹配。

尝试:

import datetime
print(datetime.datetime.strptime('2018-04-24T16:42:17Z', '%Y-%m-%dT%H:%M:%SZ'))

输出:

2018-04-24 16:42:17