python - 如何编写和阅读日期时间词典

标签 python json datetime 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())]}

尝试使用 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 中正确的方法是使用自定义编码器。您可以选择您的格式(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)

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

关于python - 如何编写和阅读日期时间词典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44630103/

相关文章:

python - 成对的 haversine 距离计算

python - 重新排序簇号以实现正确对应

json - 如何修改返回JSON

database - Go 语言中带时区的时间戳

python - 使用带有错误的距离矩阵*查找点的坐标

python - Django - 从表单小部件中删除添加新记录>

javascript - 获取第一个 JSON 结果

javascript - 将 json 数据从一个组件传递到另一组件。 Vue.js

mysql - 如何使用MySQL的MAKETIME函数构造小于1小时的负时间?

javascript - Jquery 倒计时在 Safari 中显示 NaN,在 Chrome/Firefox 中工作正常