简体   繁体   English

如何编写 python 代码以获取特定日期的所有数据?

[英]How to write a python code to get all the data from a particular date?

I have json file which has a list of ids and date.我有 json 文件,其中包含 id 和日期列表。 How to write a python program to print all the ids for a particular month from the json file如何编写 python 程序以打印 json 文件中特定月份的所有 id

Below is the sample json data以下是样本 json 数据

{
  "entities": [
    {
      "Fields": [
        {
          "Name": "version",
          "values": [
            {
              "value": "Cycle 1"
            }
          ]
        },
        {
          "Name": "subject",
          "values": [
            {
              "value": "1008"
            }
          ]
        },
        {
          "Name": "project",
          "values": [
            {}
          ]
        },
        {
          "Name": "linkage",
          "values": [
            {
              "value": "N"
            }
          ]
        },
        {
          "Name": "cycle-id",
          "values": []
        },
        {
          "Name": "creation-time",
          "values": [
            {
              "value": "2016-07-12"
            }
          ]
        },
        {
          "Name": "id",
          "values": [
            {
              "value": "1"
            }
          ]
        }]}]}

I have just tried to load the json file from below code.我刚刚尝试从下面的代码加载 json 文件。

import json

f = open('defects-export-0-100.json')

data = json.load(f)
print(data)

# month = str("MM")
month = '09'
defect_items = []
defectIDs = []

for item in data["entities"]:
    for container in item["Fields"]:
        if container["Name"] == "creation-time":
            if container["values"][0]["value"].split("-")[1] == month:
                defect_items.append(item)

for item in defect_items:
    for container in item["Fields"]:
        if container["Name"] == "id":
            defectIDs.append(container["values"][0]["value"])

My desired output: All the IDs from the one particular month of creation date.我想要的 output:创建日期特定月份的所有 ID。

The biggest issue is how you're referencing keys in a dictionary.最大的问题是您如何引用字典中的键。 You can get the value at a particular key with:您可以通过以下方式获取特定键的值:

x = {"key": value}
x["key"]
# value

I've made some assumptions about your data set, but this code works with the sample you gave.我对您的数据集做了一些假设,但是此代码适用于您提供的示例。

import json

with open("data.txt", "r") as f:
    data = json.load(f)

#month = str("MM")
month = "07"
defect_items = []
defectIDs = []

# Loop through each entity
for item in data["entities"]:
    # Loop through each field
    for container in item["Fields"]:
        # Find the field with the name "creation-item"
        if container["Name"] == "creation-time":
            # Check if the value matches with the desired date
            # Assuming there can only be one value
            if container["values"][0]["value"].split("-")[1] == month:
                defect_items.append(item)

# Loop through the defective items
for item in defect_items:
    # Loop through the fields
    for container in item["Fields"]:
        # Find the field with the name "id"
        if container["Name"] == "id":
            # Grab the value
            # Assuming there can only be one value
            defectIDs.append(container["values"][0]["value"])

Once the data is loaded, you can interact with it as you would any Python object.加载数据后,您可以与任何 Python object 进行交互。 Get all the items with:获取所有项目:

items = data['entities']

For the code below to work, create a variable month and set it to a string with the format MM (where M is a digit of the month: eg month='01' for January) so it exactly matches the correct month format of the data.要使下面的代码正常工作,请创建一个变量month并将其设置为格式为MM的字符串(其中M是月份的数字:例如, month='01'表示一月),因此它与正确的月份格式完全匹配数据。

Then, run the following loop to collect the IDs:然后,运行以下循环来收集 ID:

ids = []
for item in items.keys():

    id = None
    time = False

    for container in items[item].keys():
        if items[item][container]['Name'] == 'creation-time':
            if items[item][container]['values']['value'].split('-')[1] == month:
                time = True
        if items[item][container]['Name'] == 'id':
            id = items[item][container]['values']['value']

    if time and id: ids.append(id)

暂无
暂无

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

相关问题 如何编写 pymongo 查询以获取基于日期时间的所有数据 Python - How to write pymongo query to get all the data based on date time Python 如何根据 Python 中的特定日期提取前 2 年的数据? - How to extract data from previous 2 years based on particular date in Python? 如何使用 python 脚本从文件中获取特定数据? - how to get particular data from the file using the python script? 通过python从Postgresql数据库获取特定的日期日期 - Get the particular date date from Postgresql database through python 如何使用python获取ms Access中当前日期的所有数据? - How to get all the data for the current date in ms Access using python? 在python中以特定格式获取日期 - Get Date in a particular format in python 根据日期存储在目录中的数据。 如何获取从date1到date2的所有数据? - Data stored in directories based on date. How to get all data from date1 until date2? 如何使用python获取收到的Outlook邮件的日期和时间并检查来自特定发件人的正文 - How to get date & time of received outlook mail and check body from particular sender using python 如何编写python代码从“.bag”文件中读取数据并在bag文件运行时写入数据 - How to write a python code to read data from “.bag” file and write data in bag file runtime 从python WMI获取特定(用户)SID的所有visualsvn权限 - Get all visualsvn permissions for particular (user)SID from python WMI
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM