-1

I want to know if there is a way to write the date as DateTime format in JSON. I have followed so many links on the internet but everywhere date is converted to string(str) in order to write it on JSON file.

I used the below code:

import json
fileName='json_output.json'
def writeToJSONFile(data):
    with open(fileName, 'a+') as fp:
        json.dump(data, fp, indent=4, default=str)

then calling it as :

from datetime import datetime
date_value="09-23-2019"
date_time = datetime.strptime(date_value,'%m-%d-%Y')
date_dict={"eventDate":date_time}
writeToJSONFile(date_dict)

The above code is able to write date into the JSON file but in the string format.

I have already went through link:

How to overcome "datetime.datetime not JSON serializable"?

JSON datetime between Python and JavaScript

I just want to know if it is possible or not at all possible to store date as datetime format?

Slickmind
  • 442
  • 1
  • 7
  • 15

1 Answers1

0

Simple answer is No, JSON does not have a native datetime representation, so it will appear as a string; however, if you use a standard that is agreed upon, the receiving application can parse the variable into a datetime object, if they choose to. If you do not know what format they may agree with, I would recommend just making it a standard ISO 8601(Combined date and time in UTC), that way it can be parsed by the receiver, and retain the correct value regardless of time zone.

Defiant_1
  • 16
  • 1