简体   繁体   English

使用python读取json字符串的特定部分

[英]Read specific part of json string with python

I am currently working on a programme within the django environment which operates off a json api provided by a third party. 我目前正在django环境中开发一个程序,该程序通过第三方提供的json API运行。 There is an object within that API which I want however the string of information it provides is too much for me. 我想要该API中有一个对象,但是它提供的信息串对我来说太多了。

The data I want is the created_at tag from the twitter api using tweepy. 我想要的数据是使用tweepy从twitter api获得的created_at标记。 This created_at contains data in the following format: 此created_at包含以下格式的数据:

"created_at": "Mon Aug 27 17:21:03 +0000 2012"

This is all fine however this will return the date AND time whereas I simply want the the time part of the above example ie 17:21:03. 一切都很好,但是这将返回日期和时间,而我只是想要上面示例的时间部分,即17:21:03。

Is there any way I can just take this part of the created_at response string and store it in a separate variable? 有什么办法可以让我把这部分内容放在created_at响应字符串中,并将其存储在单独的变量中?

You can use the dateutil module 您可以使用dateutil模块

from dateutil import parser

created_at = "Mon Aug 27 17:21:03 +0000 2012"
created_at = parser.parse(created_at)
print created_at.time()

Output: 输出:

17:21:03

Try below code. 尝试下面的代码。

my_datetime = response_from_twitter['created_at']
my_time = my_datetime.split(' ')[3]

# my_time will now contain time part.

您可以将字符串拆分成一个列表并采用第4个元素:

time = source['created_at'].split(' ')[3]

What about a regular expression with re.search() : 带有re.search()的正则表达式呢:

>>> import re
>>> d = {"created_at": "Mon Aug 27 17:21:03 +0000 2012"}
>>> re.search('\d{2}:\d{2}:\d{2}', d['created_at']).group(0)
'17:21:03'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM