Skip to content

Instantly share code, notes, and snippets.

@theikkila
Created September 2, 2017 08:04
Show Gist options
  • Save theikkila/800bba403d5ed618030eedb69b8defde to your computer and use it in GitHub Desktop.
Save theikkila/800bba403d5ed618030eedb69b8defde to your computer and use it in GitHub Desktop.
from datetime import datetime
import pytz
import requests
today = datetime.now().strftime('%Y-%m-%d')
API_URL = 'https://rata.digitraffic.fi/api/v1/trains/{}'.format(today)
r = requests.get(API_URL)
helsinki = pytz.timezone('Europe/Helsinki')
DEPARTURE_STATION = 'HKI'
ARRIVAL_STATION = 'TPE'
def tsconv(dt):
fmt = '%Y-%m-%dT%H:%M:%S.%fZ'
return datetime.strptime(dt, fmt).astimezone(helsinki)
ok_trains = []
for train in r.json():
dep_sc = None
arr_sc = None
for station in train['timeTableRows']:
if station['stationShortCode'] == DEPARTURE_STATION:
dep_sc = station['scheduledTime']
if station['stationShortCode'] == ARRIVAL_STATION:
arr_sc = station['scheduledTime']
break
if dep_sc and arr_sc:
ok_trains.append((train['trainType'],
train['trainNumber'],
dep_sc,
arr_sc))
for ttype, tnum, depart, arriv in sorted(ok_trains, key=lambda x: x[2]):
print(ttype, tnum)
print(DEPARTURE_STATION, tsconv(depart))
print(ARRIVAL_STATION, tsconv(arriv))
print("=============")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment