0

How do I convert Python DateTime in JSON format?

input

from datetime import datetime
my_date = datetime.now()

output

{
   "start_date": '2020-05-06T09:27:51.386383'
}
2
  • You don't mention initial/input string. We can only speculate about it Commented May 6, 2018 at 7:36
  • Dates aren't put into "JSON format". It's just a string. Also, you're being downvoted here because date formatting and parsing is 1) answered before 2) documented enough in the python docs 3) you've not specified an exact format, so are we supposed to guess ISO8601? Commented May 6, 2018 at 7:36

1 Answer 1

15

You can't use a datetime object directly in the JSON, you'll need to convert it to a string format first before you can use it.

Use strftime to convert datetime object to string.

In [1]: from datetime import datetime                                                                                                              

In [2]: {'start_date': datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f')}                                                                            
Out[2]: {'start_date': '2021-01-27T11:10:00.489530'}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.