如何编写和读取日期时间字典

Ami*_*off 3 python datetime json dictionary eval

我需要一种有效的方法来编写包含字典(包括日期时间)的文件,然后能够将它们作为字典读取。像这样的字典:

my_dict = {'1.0': [datetime.datetime(2000, 1, 1, 0, 0, 0, 000000, tzinfo=tzutc())], '2.0': [datetime.datetime(2000, 1, 1, 0, 0, 0, 000000, tzinfo=tzutc())]}
Run Code Online (Sandbox Code Playgroud)

尝试使用 json 转储:

with open("my_file.json", 'w+') as f:
    json.dump(my_dict, f)
Run Code Online (Sandbox Code Playgroud)
TypeError: Object of type 'datetime' is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

还尝试将整个 dict 写为一个字符串,然后用 yaml 导入它,这几乎有效,但索引混乱。

with open("my_file", 'w+') as f:
    f.write(str(my_dict))

with open("my_file", 'r') as f:
    s = f.read()
    new_dict = yaml.load(s)

print(new_dict['1.0'][0])
Run Code Online (Sandbox Code Playgroud)
Output:   datetime.datetime(2000
Expected: 2000-01-01 00:00:00+00:00
Run Code Online (Sandbox Code Playgroud)

Phi*_*per 5

您可能会觉得它很笨拙,但在 python 中正确的方法是使用自定义编码器。你可以选择你的格式(iso here 但我建议在你的例子中使用 datetime.date() 。

from datetime import date,datetime
import json, re

class DateTimeAwareEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime):
            return o.isoformat()

        return json.JSONEncoder.default(self, o)

json.dumps(yourobj, cls=DateTimeAwareEncoder)
Run Code Online (Sandbox Code Playgroud)

如何使用自定义解码器要复杂得多,通常最好通过加载json.loads然后转换已知密钥来避免使用自定义解码器。