Search code examples
pythonpython-3.xdatetimeiso8601strptime

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


I want to convert a datetime string to datetime object which will be further processed to display in a different format.

The string is in the for, 2018-04-24T16:42:17Z.

I have tried the following method but it gives error.

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'

Please help.


Solution

  • You have some mismatch in your string representation of your datetime.

    Try:

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

    Output:

    2018-04-24 16:42:17