【发布时间】:2020-02-03 15:18:00
【问题描述】:
我正在尝试从该端点提取数据:https://developer.keeptruckin.com/reference#get-logs
到目前为止,我已经完成的是获取驱动程序日志的所有状态更改以及与这些更改相关的事件。我现在只想显示每个司机每天的第一个和最后一个事件,并跳过每个司机之间的所有事件,但似乎无法理解如何做到这一点。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests
import json
import csv
import math
url='https://api.keeptruckin.com/v1/logs?start_date=2020-01-20&end_date=2020-02-03'
header={'x-api-key':'API_KEY_HERE','x-time-zone':'Pacific Time (US & Canada)'}
r=requests.get(url,headers=header)
result=r.json()
result = json.loads(r.text)
num_pages=math.ceil((result['pagination']['total'])/100)
for page in range (1,num_pages):
r=requests.get(url,headers=header, params={'page_no': page,'per_page':'100'})
result=r.json()
result = json.loads(r.text)
csvheader=['First Name','Last Name','Date','Time','Type','Location','Vehicle']
with open('test.csv', 'a+', newline='') as csvfile:
writer = csv.writer(csvfile, csv.QUOTE_ALL)
##writer.writerow(csvheader)
for log in result['logs']:
username = log['log']['driver']['username']
first_name=log['log']['driver']['first_name']
last_name=log['log']['driver']['last_name']
for vehicle in log['log']['vehicles']:
number=vehicle['vehicle']['number']
for event in log['log']['events']:
start_time = event['event']['start_time']
date, time = start_time.split('T')
time1,time2=time.split('-')
event_type = event['event']['type']
location = event['event']['location']
if not location:
location = "N/A"
if (event_type=="on_duty" or event_type=="driving" or event_type=="off_duty"):
writer.writerow((first_name, last_name,date, time1, event_type, location, number))
在这一步之后,我想要实现的是,一旦我为每个驱动程序设置了第一个和最后一个事件,我想找到这两个事件之间的时间差并将其添加到一个新列中。
【问题讨论】:
-
至少包括你得到的JSON的结构,从你的代码很难理解。
-
@vkSinha 我粘贴的链接中提供了代码的结构(示例响应)。
标签: python json python-3.x python-requests nested-lists