75 lines
2.3 KiB
Python
75 lines
2.3 KiB
Python
import requests
|
|
import pandas as pd
|
|
import os
|
|
from datetime import datetime
|
|
import time
|
|
import pytz
|
|
|
|
OD_FILE = "./ods.csv"
|
|
|
|
TOMTOM_OUTPUT_FILE = "./tomtom.csv"
|
|
TOMTOM_API_KEY = "TODO"
|
|
|
|
def csv(file_path, dataframe):
|
|
if not os.path.exists(file_path):
|
|
dataframe.to_csv(file_path, index=False, header=True)
|
|
else:
|
|
dataframe.to_csv(file_path, mode="a", index=False, header=False)
|
|
|
|
|
|
def tomtom_requests():
|
|
utc_now = datetime.utcnow().replace(tzinfo=pytz.utc)
|
|
paris_tz = pytz.timezone("Europe/Paris")
|
|
paris_now = utc_now.astimezone(paris_tz)
|
|
if not (
|
|
(6 <= paris_now.hour < 10)
|
|
or (16 <= paris_now.hour < 20)
|
|
or (paris_now.hour == 10 and paris_now.minute == 0)
|
|
or (paris_now.hour == 20 and paris_now.minute == 0)
|
|
):
|
|
# Run only the requests between 6 a.m. and 10 a.m. and between 4 p.m. and 8 p.m.
|
|
print("Skipping TomTom requests")
|
|
return
|
|
ods = pd.read_csv(OD_FILE)
|
|
data = list()
|
|
for _, row in ods.iterrows():
|
|
url1 = "https://api.tomtom.com/routing/1/calculateRoute/"
|
|
orig_des = (
|
|
str(row["origin_y"])
|
|
+ ","
|
|
+ str(row["origin_x"])
|
|
+ ":"
|
|
+ str(row["destination_y"])
|
|
+ ","
|
|
+ str(row["destination_x"])
|
|
+ "/json?"
|
|
)
|
|
apikey = f"key={TOMTOM_API_KEY}"
|
|
depart_time = "&departAt=now"
|
|
travelmode = "&travelMode=car"
|
|
url = url1 + orig_des + apikey + depart_time + travelmode
|
|
output = requests.request("GET", url, headers={})
|
|
time.sleep(0.5)
|
|
output = output.json()
|
|
if "routes" in output.keys():
|
|
duration = output["routes"][0]["summary"]["travelTimeInSeconds"]
|
|
distance = output["routes"][0]["summary"]["lengthInMeters"]
|
|
else:
|
|
duration = 0
|
|
distance = 0
|
|
row = {
|
|
"origin": row["zone_origin"],
|
|
"destination": row["zone_destination"],
|
|
"date": paris_now.strftime("%Y-%m-%d"),
|
|
"departure_time": paris_now.strftime("%H:%M"),
|
|
"travel_time": time.strftime("%H:%M:%S", time.gmtime(duration)),
|
|
"distance": distance,
|
|
}
|
|
data.append(row)
|
|
df = pd.DataFrame(data)
|
|
csv(TOMTOM_OUTPUT_FILE, df)
|
|
print("Done")
|
|
|
|
|
|
tomtom_requests()
|