-3

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Boudhayan Dev
  • 970
  • 4
  • 14
  • 42
  • Why is it getting downvoted ? – Boudhayan Dev Apr 24 '18 at 17:56
  • 1
    The format string you're trying to use isn't even remotely close to the format you're trying to parse. Look at [the docs](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior). Why did you think `%b` ("Month as locale’s abbreviated name") would match `2018`, a space would match a hyphen, etc.? – abarnert Apr 24 '18 at 17:57
  • Got ahead https://stackoverflow.com/questions/466345/converting-string-into-datetime –  Apr 24 '18 at 17:57
  • But you're supposed to give the format of the string you're trying to process, which clearly starts with a year. – roganjosh Apr 24 '18 at 17:57
  • The error is pretty straightforward. The format you passed in (the second argument) doesn't work for the string you are parsing (the first argument). Why did you expect that format string to work? Please share your research. Did you read the documentation on how `datetime.strptime()` works? – Martijn Pieters Apr 24 '18 at 17:59
  • Yeah I missed that part I guess. Thanks anyway. – Boudhayan Dev Apr 24 '18 at 18:02

1 Answers1

2

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
Rakesh
  • 81,458
  • 17
  • 76
  • 113