Skip to main content
 首页 » 编程设计

python之在 python 中使用 bson.json_util.loads 时如何忽略时区

2024年10月17日8del

我正在将 bson 转储并加载到文本文件中,并且我的日期时间中添加了时区信息。我不想添加时区信息。

import bson, datetime 
d1 = datetime.datetime.now() 
d2 = bson.json_util.loads(bson.json_util.dumps(d1)) 

d1 中的结果:

datetime.datetime(2016, 8, 16, 14, 38, 41, 984544) 

和d2:

datetime.datetime(2016, 8, 16, 14, 56, 10, 155000, tzinfo=<bson.tz_util.FixedOffset object at 0x1042ca050>) 

在这种特殊情况下我可以做

d3 = d2.replace(tzinfo=None) 

删除时区。但是,我正在为一个更大的对象做这个,在其他类型中到处都是时间。有没有办法指示 bson.json_util.loads 在尝试解析日期时间时始终设置 tzinfo=None?

请您参考如下方法:

很有趣。 bson 源代码直接覆盖了 object_hook,因此您无法传入自定义的。

来自source here :

def loads(s, *args, **kwargs): 
    """Helper function that wraps :class:`json.loads`. 
    Automatically passes the object_hook for BSON type conversion. 
    """ 
    kwargs['object_hook'] = lambda dct: object_hook(dct) 
    return json.loads(s, *args, **kwargs) 

它们的来源(在 object_hook 内)也明确设置了时区,这导致了您所看到的行为:

aware = datetime.datetime.strptime( 
            dt, "%Y-%m-%dT%H:%M:%S.%f").replace(tzinfo=utc) 
 
if not offset or offset == 'Z': 
    # UTC 
    return aware 

如果您绝对不能设置时区,我认为您将不得不再次传递结果数据集以删除时区。

编辑:看起来有一个 pending change添加一个 JsonOptions 类,允许您传递 tz_aware=False。因此,如果您可以等到 python 驱动程序更新到 3.4,您应该能够获得所需的行为。