获取 JSON 列表中的第一个和最后一个元素并找出时差

Getting the first and last elements in a JSON list and finding the time difference

我正在尝试从此端点提取数据:https://developer.keeptruckin.com/reference#get-logs

到目前为止,我已经完成的工作是获取 driver 日志的所有状态更改以及与这些相关的事件。我现在只想显示每天每个 driver 的第一个和最后一个事件,并跳过每个 driver 之间的所有事件,但似乎无法理解如何做到这一点。

#!/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))

在这一步之后,我想要实现的是,一旦我有了每个 driver 的第一个和最后一个事件,我想找到这两个事件之间的时间差,并将其添加到一个新的柱子。

您可以使用 dateutil.parser 解析您的字符串,它将为您提供 datetime 对象。 然后,您可以将有关事件的所有必要信息保存在列表中,包括 datetime 对象,其中列表中的每个条目都是一个包含有关 events.Then 的所有信息的元组,您可以根据 datetime 对象对列表进行排序。您可以从列表中取出第一个和最后一个事件。两个日期时间对象之间的差异将为您提供时间增量,可以轻松将其转换为秒。

from dateutil.parser import parse
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']
        events = []
        for event in log['log']['events']:
            start_time = parse(event['event']['start_time'])
            end_time = parse(event['event']['end_time'])


            location = event['event']['location']
            # add all data as tuple you want to save for event
            events.append((start_time,end_time, location))
        #sort based on first element of tuple -- start_time
        events.sort(key=lambda x: x[0])      
        first_event = events[0]
        last_event = events[-1]
        #time difference in seconds
        time_diff = (first_event[0]-last_event[0]).seconds # first_event[0] -- start time