如何使用JSON.loads转换为Python datetime对象? [英] How to convert to a Python datetime object with JSON.loads?

查看:497
本文介绍了如何使用JSON.loads转换为Python datetime对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON对象的字符串表示。

I have a string representation of a JSON object.

dumped_dict = '{"debug": false, "created_at": "2020-08-09T11:24:20"}'

当我调用json.loads这个对象;

When I call json.loads with this object;

json.loads(dumped_dict)

我得到;

{'created_at': '2020-08-09T11:24:20', 'debug': False}

这里没有错。但是,我想知道是否有办法将json.loads的上述对象转换成如下:

There is nothing wrong in here. However, I want to know if there is a way to convert the above object with json.loads to something like this:

{'created_at': datetime.datetime(2020, 08, 09, 11, 24, 20), 'debug': False}

很快,我们能够将datetime字符串转换为实际的datetime.datetime对象,而
调用json.loads?

Shortly, are we able to convert datetime strings to actual datetime.datetime objects while calling json.loads?

推荐答案

我的解决方案到目前为止:

My solution so far:

>>> json_string = '{"last_updated": {"$gte": "Thu, 1 Mar 2012 10:00:49 UTC"}}'
>>> dct = json.loads(json_string, object_hook=datetime_parser)
>>> dct
{u'last_updated': {u'$gte': datetime.datetime(2012, 3, 1, 10, 0, 49)}}


def datetime_parser(dct):
    for k, v in dct.items():
        if isinstance(v, basestring) and re.search("\ UTC", v):
            try:
                dct[k] = datetime.datetime.strptime(v, DATE_FORMAT)
            except:
                pass
    return dct

有关使用object_hook的更多参考: JSON编码器和解码器

For further reference on the use of object_hook: JSON encoder and decoder

在我的情况下,json字符串来自GET请求到我的REST API。该解决方案允许我透明地获取日期,而不要强迫客户端和用户将硬编码前缀如 __ date __ 到JSON中,只要输入字符串符合DATE_FORMAT即可是:

In my case the json string is coming from a GET request to my REST API. This solution allows me to 'get the date right' transparently, without forcing clients and users into hardcoding prefixes like __date__ into the JSON, as long as the input string conforms to DATE_FORMAT which is:

DATE_FORMAT = '%a, %d %b %Y %H:%M:%S UTC'

正则表达式模式应该进一步改进

The regex pattern should probably be further refined

PS:如果你想知道,json_string是一个MongoDB / PyMongo查询。

PS: in case you are wondering, the json_string is a MongoDB/PyMongo query.

这篇关于如何使用JSON.loads转换为Python datetime对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆