Traffine I/O

Bahasa Indonesia

2023-05-13

Memuat Data GTFS Realtime dalam Python

Memuat GTFS Realtime dalam Python

Data GTFS Realtime berbentuk data biner. Di Python, Anda dapat mengekstrak data ini menggunakan pustaka yang disebut gtfs-realtime-bindings.

Instalasi gtfs-realtime-bindings

Anda dapat menginstal gtfs-realtime-bindings dengan perintah berikut:

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

Ekstraksi Data

Mari mencoba mengekstrak data GTFS Realtime untuk Prefektur Hiroshima menggunakan kode berikut:

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"
    }
  }
}
.
.
.

Anda dapat mengakses header dan entity sebagai berikut:

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
.
.
.
]

Anda dapat melihat bahwa entity adalah tipe daftar (list).

Referensi

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!