【发布时间】:2017-11-21 15:25:33
【问题描述】:
我需要一种有效的方法来编写包含字典(包括日期时间)的文件,然后能够将它们作为字典读取。像这样的字典:
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
【问题讨论】:
标签: python json datetime dictionary eval