0

I'm simply trying to convert a date-string to a date:

import datetime
exampleDate = 'Jul 8 2021'
datetime.datetime.strptime(exampleDate, '%b %d %Y')

However, I'm later outputting this to a json, and i'm getting an error:

datetime.datetime(2021, 7, 8, 0, 0) is not JSON serializable

Can confirm in Python console that exampleDate is not printing out as a date, but rather in this serialized fashion. All I want is: 2021-07-08.

halfer
  • 19,824
  • 17
  • 99
  • 186
DiamondJoe12
  • 1,879
  • 7
  • 33
  • 81
  • 4
    Does this answer your question? [How to overcome "datetime.datetime not JSON serializable"?](https://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable) – cbrxyz Jul 08 '21 at 03:12
  • I tried to read this info - converting to str() did not work for me.. – DiamondJoe12 Jul 08 '21 at 03:35
  • 1
    Converting to string definitely works. You must have made a mistake. Show us the code and the full error traceback. – John Gordon Jul 08 '21 at 03:44

1 Answers1

0

Because you cannot put datetime.datetime to JSON. You will need to format that to a string.

d = datetime.datetime.strptime(exampleDate, '%b %d %Y')

type(d) is datetime.datetime

Now let's convert that to a string with strftime:

date_str = d.strftime("%Y-%m-%d")
print(date_str)

You get the format you expected: 2021-07-08. Then you put this to JSON.

Cabara
  • 336
  • 4
  • 12