-1

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'
}
rmaleki
  • 581
  • 1
  • 9
  • 31
  • You don't mention initial/input string. We can only speculate about it – Andy K May 06 '18 at 07: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? – OneCricketeer May 06 '18 at 07:36

1 Answers1

15

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'}
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81