python 使用循环提取同一时间的数据
时间: 2024-04-30 10:22:33 浏览: 44
Python提取特定时间段内数据的方法实例
5星 · 资源好评率100%
假设有以下数据:
```
data = [
{"time": "2021-01-01 09:00:00", "value": 10},
{"time": "2021-01-01 09:05:00", "value": 20},
{"time": "2021-01-01 09:10:00", "value": 30},
{"time": "2021-01-01 09:15:00", "value": 40},
{"time": "2021-01-01 09:20:00", "value": 50},
{"time": "2021-01-01 09:25:00", "value": 60},
{"time": "2021-01-01 09:30:00", "value": 70},
{"time": "2021-01-01 09:35:00", "value": 80},
{"time": "2021-01-01 09:40:00", "value": 90},
{"time": "2021-01-01 09:45:00", "value": 100},
{"time": "2021-01-01 09:50:00", "value": 110},
{"time": "2021-01-01 09:55:00", "value": 120},
{"time": "2021-01-02 09:00:00", "value": 10},
{"time": "2021-01-02 09:05:00", "value": 20},
{"time": "2021-01-02 09:10:00", "value": 30},
{"time": "2021-01-02 09:15:00", "value": 40},
{"time": "2021-01-02 09:20:00", "value": 50},
{"time": "2021-01-02 09:25:00", "value": 60},
{"time": "2021-01-02 09:30:00", "value": 70},
{"time": "2021-01-02 09:35:00", "value": 80},
{"time": "2021-01-02 09:40:00", "value": 90},
{"time": "2021-01-02 09:45:00", "value": 100},
{"time": "2021-01-02 09:50:00", "value": 110},
{"time": "2021-01-02 09:55:00", "value": 120},
]
```
要提取同一时间(小时和分钟相同)的数据,可以使用 Python 的循环和条件语句。
```python
result = {}
for item in data:
time = item["time"]
hour_min = time[11:16] # 截取时间中的小时和分钟部分
if hour_min not in result:
result[hour_min] = []
result[hour_min].append(item)
print(result)
```
输出结果为:
```
{
"09:00": [
{"time": "2021-01-01 09:00:00", "value": 10},
{"time": "2021-01-02 09:00:00", "value": 10}
],
"09:05": [
{"time": "2021-01-01 09:05:00", "value": 20},
{"time": "2021-01-02 09:05:00", "value": 20}
],
"09:10": [
{"time": "2021-01-01 09:10:00", "value": 30},
{"time": "2021-01-02 09:10:00", "value": 30}
],
"09:15": [
{"time": "2021-01-01 09:15:00", "value": 40},
{"time": "2021-01-02 09:15:00", "value": 40}
],
"09:20": [
{"time": "2021-01-01 09:20:00", "value": 50},
{"time": "2021-01-02 09:20:00", "value": 50}
],
"09:25": [
{"time": "2021-01-01 09:25:00", "value": 60},
{"time": "2021-01-02 09:25:00", "value": 60}
],
"09:30": [
{"time": "2021-01-01 09:30:00", "value": 70},
{"time": "2021-01-02 09:30:00", "value": 70}
],
"09:35": [
{"time": "2021-01-01 09:35:00", "value": 80},
{"time": "2021-01-02 09:35:00", "value": 80}
],
"09:40": [
{"time": "2021-01-01 09:40:00", "value": 90},
{"time": "2021-01-02 09:40:00", "value": 90}
],
"09:45": [
{"time": "2021-01-01 09:45:00", "value": 100},
{"time": "2021-01-02 09:45:00", "value": 100}
],
"09:50": [
{"time": "2021-01-01 09:50:00", "value": 110},
{"time": "2021-01-02 09:50:00", "value": 110}
],
"09:55": [
{"time": "2021-01-01 09:55:00", "value": 120},
{"time": "2021-01-02 09:55:00", "value": 120}
]
}
```
可以看到,同一时间的数据被提取出来并存储在字典中。每个键对应的值是一个列表,包含了所有该时间点的数据。
阅读全文