我需要一种有效的方式来编写包含日期时间的字典的文件,然后能够将它们作为字符读取。类型的字典这样的:如何编写和读取日期时间字典
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
也试着写整个字典作为一个字符串,然后用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
我喜欢这种方法,是比我预期的要快得多 – Aminoff