2023-05-13

Loading GTFS Realtime in Python

Loading GTFS Realtime in Python

GTFS Realtime data is in binary format. In Python, you can extract this data using a library called gtfs-realtime-bindings.

Installing gtfs-realtime-bindings

You can install gtfs-realtime-bindings with the following command:

bash
$ pip install --upgrade gtfs-realtime-bindings

Data Extraction

Let's try to extract GTFS Realtime data for Hiroshima Prefecture using the following code:

python
from google.transit import gtfs_realtime_pb2
import urllib.request, urllib.error
feed = gtfs_realtime_pb2.FeedMessage()
url = "https://ajt-mobusta-gtfs.mcapps.jp/realtime/11/vehicle_position.bin" # GTFS Realtime url
with urllib.request.urlopen(url) as res:
    feed.ParseFromString(res.read())
    print(feed)
header {
  gtfs_realtime_version: "1.0"
  incrementality: FULL_DATASET
  timestamp: 1694429284
}
entity {
  id: "ac2686d0-aad6-4e99-acce-4c9ecdceaf97"
  is_deleted: false
  vehicle {
    trip {
      trip_id: "5ee8068b-63a2-4f33-9b70-260ce9343bed"
      schedule_relationship: SCHEDULED
      route_id: "3093754835"
    }
    position {
      latitude: 34.4449348449707
      longitude: 132.6889190673828
      bearing: 179.0
      speed: 9.0
    }
    timestamp: 1694429269
    vehicle {
      id: "3152"
    }
  }
}
.
.
.

You can access the header and entity as follows:

python
from google.transit import gtfs_realtime_pb2
import urllib.request, urllib.error
feed = gtfs_realtime_pb2.FeedMessage()
url = "https://ajt-mobusta-gtfs.mcapps.jp/realtime/11/vehicle_position.bin"
with urllib.request.urlopen(url) as res:
    feed.ParseFromString(res.read())
    print('*****header*****')
    print(feed.header)
    print('*****entity*****')
    print(feed.entity)
*****header*****
gtfs_realtime_version: "1.0"
incrementality: FULL_DATASET
timestamp: 1694429406

*****entity*****
[id: "ac2686d0-aad6-4e99-acce-4c9ecdceaf97"
is_deleted: false
vehicle {
  trip {
    trip_id: "5ee8068b-63a2-4f33-9b70-260ce9343bed"
    schedule_relationship: SCHEDULED
    route_id: "3093754835"
  }
  position {
    latitude: 34.4449348449707
    longitude: 132.6889190673828
    bearing: 179.0
    speed: 9.0
  }
  timestamp: 1694429269
  vehicle {
    id: "3152"
  }
}
, id: "e79e318b-1875-4100-8f61-973077830d5a"
is_deleted: false
.
.
.
]

You can see that entity is of type list.

References

https://www.bus-kyo.or.jp/gtfs-open-data
https://developers.google.cn/transit/gtfs-realtime/examples/python-sample

Ryusei Kakujo

researchgatelinkedingithub

Focusing on data science for mobility

Bench Press 100kg!