<分区>
我需要一种有效的方法来编写包含字典(包括日期时间)的文件,然后能够将它们作为字典读取。像这样的口述:
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())]}
尝试使用 json 转储:
with open("my_file.json", 'w+') as f:
json.dump(my_dict, f)
TypeError: Object of type 'datetime' is not JSON serializable
还尝试将整个 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])
Output: datetime.datetime(2000
Expected: 2000-01-01 00:00:00+00:00