Skip to content

Instantly share code, notes, and snippets.

@flibbertigibbet
Created December 23, 2014 22:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flibbertigibbet/53b1fb43f3ca112d4964 to your computer and use it in GitHub Desktop.
Save flibbertigibbet/53b1fb43f3ca112d4964 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
""" Parse JSON real-time bus data from SEPTA:
http://www3.septa.org/hackathon/
"""
from datetime import datetime, timedelta
import json
import requests
import sys
bus_flds = ['lat', 'lng', 'label', 'VehicleID', 'BlockID', 'Direction', 'destination', 'Offset']
date_fmt = '%B %d, %Y, %I:%M %p'
# to fetch the latest:
r = requests.get('http://www3.septa.org/hackathon/TransitViewAll')
if r.ok:
j = r.json()
else:
print('oh noes! could not fetch realtime data.')
sys.exit(1)
# or, to read from file:
# f = open('bus.json', 'rb')
# data = f.read()
# f.close()
# j = json.loads(data)
read_at = j.keys()[0]
read_dt = datetime.strptime(read_at, date_fmt)
busct = 0
for itm in j[read_at]:
inner_keys = itm.keys()
for key in inner_keys:
inner_list = itm[key]
for bus in inner_list:
# subtract Offset minutes from read_at time to get time bus was at location
recorded_at = read_dt - timedelta(minutes=int(bus['Offset']))
# label seems to generally be the same as bus ID
busct += 1
print('\n')
for fld in bus_flds:
print('%s : %s' % (fld, bus[fld]))
print('\ngot %s buses' % busct)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment