【问题标题】:How to write and read datetime dictionaries [duplicate]如何编写和阅读日期时间字典[重复]
【发布时间】: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


    【解决方案1】:

    您可以使用Pickle。它用于序列化和反序列化 Python 对象结构。 python 中的任何对象都可以腌制,以便可以将其保存在磁盘上。 pickle 所做的是它先“序列化”对象,然后再将其写入文件。 Pickling 是一种将 python 对象(list、dict 等)转换为字符流的方法。这个想法是这个字符流包含在另一个 python 脚本中重建对象所需的所有信息。 Source

    这可行:

    >>> import pickle
    >>> file_Name = "testfile"
    >>> fileObject = open(file_Name,'wb')
    >>> 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())]}
    >>> pickle.dump(my_dict, fileObject)
    >>> fileObject.close()
    >>> fileObject = open(file_Name,'r')
    >>> my_dict_loaded = pickle.load(fileObject)
    >>> my_dict_loaded
    {'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())]}
    

    【讨论】:

    • 我喜欢这种方法,比我预期的要快很多。
    【解决方案2】:

    你可以使用strftime方法:

    my_dict = {
        '1.0': [
                   datetime.datetime(
                       2000, 
                       1, 
                       1, 
                       0, 
                       0, 
                       0, 
                       000000, 
                       tzinfo=tzutc()
                  ).strftime("%Y-%m-%d %H:%M:%S")],
        '2.0': [
                  datetime.datetime(
                       2000, 
                       1, 
                       1, 
                       0, 
                       0, 
                       0, 
                       000000, 
                       tzinfo=tzutc()
                  ).strftime("%Y-%m-%d %H:%M:%S")
               ]
    

    }

    【讨论】:

      【解决方案3】:

      您可能会觉得它很笨重,但在 python 中正确的方法是使用自定义编码器。您可以选择格式(此处为 iso,但我建议在您的示例中使用 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 然后转换已知键以避免自定义解码器来处理。

      【讨论】:

      • 谢谢你。
      • 你,先生,拯救了我的一天。
      • 这个很好用,谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 2014-09-09
      • 1970-01-01
      • 2022-11-01
      • 2021-05-30
      相关资源
      最近更新 更多