Last active
July 18, 2022 23:46
-
-
Save edilAraujo/e444429a1c48acee0544b9bff88501a4 to your computer and use it in GitHub Desktop.
Get Jurisdiction Report broken down by day
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import csv | |
import datetime | |
import pytz | |
tzone = 'US/Eastern' | |
def write_CSV(row_array, filename): | |
with open(filename + '.csv', 'w') as csvfile: | |
filewriter = csv.writer(csvfile, quoting=csv.QUOTE_ALL) | |
filewriter.writerow(['Vehicle', 'Date', 'State', 'Distance (miles)', 'Toll Distance (miles)']) | |
for row in row_array: | |
filewriter.writerow(row) | |
def getVehicleList(api_key): | |
url = "https://api.samsara.com/v1/fleet/list" | |
payload={} | |
headers = {'Authorization': 'Bearer ' + api_key} | |
response = requests.request("GET", url, headers=headers, data=payload) | |
return response.json()['vehicles'] | |
def getVehicleTrips(api_key, vehicleId, startMs, endMs): | |
url = "https://api.samsara.com/v1/fleet/trips?vehicleId=" + vehicleId + "&startMs=" + startMs + "&endMs=" + endMs | |
payload={} | |
headers = {'Authorization': 'Bearer ' + api_key} | |
response = requests.request("GET", url, headers=headers, data=payload) | |
return response.json()['trips'] | |
def getFormattedDate(timeMS): | |
formattedDate = datetime.datetime.fromtimestamp(timeMS/1000.0, tz=datetime.timezone.utc) | |
return formattedDate.astimezone(pytz.timezone(tzone)).strftime('%m-%d-%Y') | |
def getJurisdictionByDate(api_key, vehicles_list, startMs, endMs): | |
output = [] | |
for vehicle in vehicles_list: | |
# Get trips for each vehicle | |
vehicles_trips = getVehicleTrips(api_key, str(vehicle['id']), startMs, endMs) | |
if (len(vehicles_trips) > 0): | |
distance = 0 #default distance and tollDistance is 0 meters | |
tollDistance = 0 | |
# Get State and TripDate from the endLocation and endMs | |
locationSplit = vehicles_trips[0]['endLocation'].split(", ") | |
state = locationSplit[-1][0:2] | |
tripDate = getFormattedDate(vehicles_trips[0]['endMs']) | |
i = 0 | |
# Look at each trip segment adding them together | |
while i < len(vehicles_trips): | |
trip = vehicles_trips[i] | |
locationSplit = trip['endLocation'].split(", ") | |
# Create a new entry if a new date is found or if crossing state lines | |
if (tripDate != getFormattedDate(trip['endMs']) or state != locationSplit[-1][0:2]): | |
output.append((vehicle['name'], tripDate, state, distance * .000621371, tollDistance * 0.000621371)) | |
distance = 0 | |
tollDistance = 0 | |
tripDate = getFormattedDate(trip['endMs']) | |
state = locationSplit[-1][0:2] | |
else: | |
if (trip['endOdometer'] > 0 and trip['startOdometer'] > 0): | |
distance = distance + (trip['endOdometer'] - trip['startOdometer']) | |
else: | |
distance = distance + trip['distanceMeters'] | |
tollDistance = tollDistance + trip['tollMeters'] | |
i += 1 | |
# Add the last segment of the loop | |
if (distance > 0 or tollDistance > 0): | |
output.append((vehicle['name'], tripDate, state, distance * .000621371, tollDistance * 0.000621371)) | |
return output | |
def main(): | |
api_key = "" # Add API key | |
startMs = "1654920000000" # June 11 inclusive | |
endMs = "1655006400000" # June 12 exclusive | |
# Get list of vehicle | |
vehicles_list = getVehicleList(api_key) | |
# Outputs a list of trips including State but not grouping days yet. For example, you may have multiple entries to CA under the same day | |
# if a driver took a trip to CA, then to NV, and then back to CA. This would be listed here as CA then NV, and then CA again. | |
# Users should group these entries in Excel with a simple pivot table where the rows would be Vehicle/Date/State and the values would be Distance/Toll Distance | |
jurisdictionOutput = getJurisdictionByDate(api_key, vehicles_list, startMs, endMs) | |
write_CSV(jurisdictionOutput, "Jurisdiction_by_day") | |
if __name__=="__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment