【问题标题】:Getting the first and last elements in a JSON list and finding the time difference获取 JSON 列表中的第一个和最后一个元素并查找时间差
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2012-06-11
    • 2023-03-09
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 2013-12-01
    • 2016-06-05
    • 2018-08-25
    • 2019-08-28
    相关资源
    最近更新 更多