如何从API返回的JSON中提取start_time最接近当前时间的对应id
实现思路
- 第一步:获取当前时间的毫秒级时间戳,用于后续差值计算
- 第二步:遍历API返回的所有数组元素,将每个元素的
start_time字段转换为时间戳,计算该时间戳与当前时间戳差值的绝对值,值越小说明距离当前时间越近 - 第三步:遍历过程中持续记录当前差值最小的条目对应的id值,遍历完成后即可得到最终结果
- 注意:如果存在多个条目差值完全相同的情况,下方代码默认返回第一个出现的符合条件的id,你可以根据需求自行调整逻辑,比如返回所有符合条件的id、或者返回id值最小的条目等
代码示例
Python 实现
import time from datetime import datetime # 此处替换为你调用API获取到的实际响应数据 api_response = [ { "expected": { "id": 1, "end_time": "2021-10-01T06:35:00.659Z", "start_time": "2021-10-01T06:35:00.659Z" } }, { "expected": { "id": 2, "end_time": "2021-09-30T17:08:29.307Z", "start_time": "2021-09-30T17:08:29.307Z" } }, { "expected": { "id": 3, "end_time": "2021-10-01T09:49:18.574Z", "start_time": "2021-10-01T09:49:18.574Z" } }, { "expected": { "id": 4, "end_time": "2021-09-30T17:08:29.303Z", "start_time": "2021-09-30T15:08:29.303Z" } }, ] current_ts = time.time() * 1000 min_diff = float('inf') target_id = None for item in api_response: start_time_str = item['expected']['start_time'] start_ts = datetime.fromisoformat(start_time_str.replace('Z', '+00:00')).timestamp() * 1000 current_diff = abs(current_ts - start_ts) if current_diff < min_diff: min_diff = current_diff target_id = item['expected']['id'] print("距离当前时间最近的条目id为:", target_id)
JavaScript 实现
// 此处替换为你调用API获取到的实际响应数据 const apiResponse = [ { "expected": { "id": 1, "end_time": "2021-10-01T06:35:00.659Z", "start_time": "2021-10-01T06:35:00.659Z" } }, { "expected": { "id": 2, "end_time": "2021-09-30T17:08:29.307Z", "start_time": "2021-09-30T17:08:29.307Z" } }, { "expected": { "id": 3, "end_time": "2021-10-01T09:49:18.574Z", "start_time": "2021-10-01T09:49:18.574Z" } }, { "expected": { "id": 4, "end_time": "2021-09-30T17:08:29.303Z", "start_time": "2021-09-30T15:08:29.303Z" } }, ] const currentTs = Date.now() let minDiff = Infinity let targetId = null apiResponse.forEach(item => { const startTs = new Date(item.expected.start_time).getTime() const currentDiff = Math.abs(currentTs - startTs) if (currentDiff < minDiff) { minDiff = currentDiff targetId = item.expected.id } }) console.log("距离当前时间最近的条目id为:", targetId)
内容的提问来源于stack exchange,提问作者pratteek shaurya
相关产品推荐
相关产品推荐

