是否可以使用 Python 在 JSON 中将日期写为 DateTime 格式而不将其转换为字符串

Is it possible to write date as DateTime format in JSON using Python without converting it to string

我想知道在JSON中是否有办法将日期写成DateTime格式。 我在互联网上关注了很多 link,但为了将其写入 JSON 文件,到处都将日期转换为字符串(str)。

我使用了下面的代码:

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

然后称它为:

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)

上面的代码能够将日期写入 JSON 文件,但是是字符串格式。

我已经通过了link:

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

JSON datetime between Python and JavaScript

我只想知道是否可以将日期存储为日期时间格式?

简单的回答是否定的,JSON 没有本地日期时间表示,因此它将显示为字符串;但是,如果您使用商定的标准,则接收应用程序可以将变量解析为日期时间对象(如果他们愿意的话)。如果您不知道他们可能同意什么格式,我建议只将其设为标准 ISO 8601(UTC 中的合并日期和时间),这样它就可以被接收方解析,并且无论时区如何都保留正确的值.