Last active 1440821022

Transperth offline bus stop data and example implementation

Revision 03d04ac2359f4e33ac6f4c512bc23be752dac96b

tpparse.py Raw
1# Data can be retrieved (gzipped) from
2# https://mega.co.nz/#!os4gjQBR!fspHcvoHZHDzN6IGtJgIXUh4N_ciIEL40tHoivqcKXg
3# Currently this data only contains info for weekdays, as of 2014-06-20. I can't make the data
4# collection process public, sadly, so please email me if you'd like saturday or sunday/holiday data.
5#
6# This is an example implementation of a program to read this data, in Python
7# It replicates Transperth's service to look up the next five bus times to a stop, as seen here
8# http://136213.mobi/Bus/StopResults.aspx?SN=14353
9# Please direct questions to steven+transperthdata@blha303.com.au
10#
11# Example output, recorded at 6:18am on a Wednesday:
12# $ tpparse.py 14353
13# 06:24: 39
14# 06:45: 39
15# 07:26: 39
16# 07:36: 39
17# 07:48: 39
18
19import json,gzip,datetime,sys
20
21def get_data():
22 with gzip.open('transperthcache.json.gz', 'rb') as f:
23 data = json.load(f)
24 return data
25
26def daycheck(date=False):
27 """For getting the correct timetable from [[weekday], [sat], [sun]]"""
28 now = date if date else datetime.datetime.now()
29 if now.isoweekday() in range(1,6):
30 return 0
31 elif now.isoweekday() in range(6,7):
32 return 1
33 elif now.isoweekday() in range(7,8):
34 return 2
35
36def next_five(data, stop, date=False):
37 """For getting the next five stops from the specified time (by default, now)"""
38 now = date if date else datetime.datetime.now()
39 try:
40 stop = str(int(stop)) # sanity checks
41 except ValueError:
42 return u"Invalid stop number: " + unicode(stop)
43 if not stop in data:
44 return unicode(stop) + u" not found in cache"
45 x = 0
46 out = u""
47 for i in data[stop][daycheck()]:
48 if x > 4:
49 break
50 if int(i[1][:2]) >= now.hour:
51 if int(i[1][3:]) >= now.minute:
52 out = out + u"{}: {}\r\n".format(i[1], i[0])
53 x += 1
54 return out.strip() if x else "No results"
55
56if __name__ == "__main__":
57 if len(sys.argv) > 1:
58 stop = sys.argv[1]
59 else:
60 stop = "14353"
61 print(next_five(get_data(), stop))
62