Skip to content

Instantly share code, notes, and snippets.

@mammuth
Created October 8, 2019 19:48
Show Gist options
  • Save mammuth/0105876a41fd19344942f465e14b28ed to your computer and use it in GitHub Desktop.
Save mammuth/0105876a41fd19344942f465e14b28ed to your computer and use it in GitHub Desktop.
MVG Live unofficial API demo.
"""
Demo / usage of the API endpoint which mvg.de uses itself.
Printed example output:
['21:58: S8 nach München Flughafen Terminal ', '22:02: S8 nach Weßling(Oberbay) ', '22:22: S8 nach Herrsching ']
"""
import requests
import datetime
station = 2 # Marienplatz
def time_until_departure(timestamp: int) -> str:
dep = datetime.datetime.fromtimestamp(timestamp/1000)
now = datetime.datetime.now()
return f'{dep - now}'
def departure_time(timestamp: int) -> str:
dep = datetime.datetime.fromtimestamp(timestamp/1000)
formatted = dep.strftime("%H:%M")
return formatted
r = requests.get(
f'https://www.mvg.de/fahrinfo/api/departure/{station}?footway=0',
# The endpoint checks for a "valid" User-Agent, so make sure to provide one
# The Auth key is taken from mvg.de
headers={'X-MVG-Authorization-Key': '5af1beca494712ed38d313714d4caff6', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'}
)
j = r.json()
prettified_departures = [
f'{departure_time(d["departureTime"])} - {d["label"]} nach {d["destination"]} '
for d in j['departures'] if d['product'] == 'SBAHN'
]
print(prettified_departures)
@jeff25
Copy link

jeff25 commented Jan 9, 2020

Hi Mammuth,

is there any change in the API from MVG? I try to use your sample but it will not work :-( Do you have any idea what i need to do?

Br,
RObert

@mammuth
Copy link
Author

mammuth commented Jan 9, 2020

You've got your answer on another thread. But for people coming here via search engines: maybe you find what you're looking for at pc-coholic/PyMVGLive#12

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment