flights/show

96 lines
2.5 KiB
Plaintext
Raw Normal View History

2023-09-09 19:50:41 +01:00
#!/usr/bin/python3
import csv
2023-09-11 06:41:07 +01:00
import os
2023-09-09 19:50:41 +01:00
from datetime import datetime, timedelta
2023-09-11 06:41:07 +01:00
from typing import Callable
2023-09-09 19:50:41 +01:00
2023-09-11 06:41:07 +01:00
backup_loc = os.path.expanduser("~/backup/openflights")
2023-09-09 19:50:41 +01:00
now = datetime.now()
since_date = now - timedelta(days=365 * 5)
airlines = {
"British Airways": "BA",
"Iberia Airlines": "IB",
"Qatar Airways": "QR",
"Ryanair": "FR",
"easyJet": "U2",
"SAS": "SK",
}
Flight = dict[str, str]
Flights = list[tuple[datetime, Flight]]
2023-09-11 06:41:07 +01:00
def get_most_recent(loc: str, pred: Callable[[str], bool] | None = None) -> str | None:
"""Get the most recent file in a directory."""
files = [f for f in os.listdir(loc) if pred is None or pred(f)]
return os.path.join(loc, max(files)) if files else None
2023-09-09 19:50:41 +01:00
def format_row(dt: datetime, f: Flight) -> str:
"""Format flight."""
d = dt.strftime("%a, %d %b %Y")
days = (dt - now).days
if days == 0 or days == -1:
delta = "today"
elif days < 0:
delta = f"{-days:>3d} days ago"
else:
delta = f"{days:>3d} days"
airline = f["Airline"]
if len(airline) > 15:
airline = "".join(t[0] for t in airline.split())
flight_number = f["Flight_Number"]
if flight_number.isdigit() and airline in airlines:
flight_number = airlines[airline] + flight_number
return (
("*" if delta == "today" else " ")
+ f' {d} {delta:>13s} {f["From"]:4s} -> {f["To"]:4s} '
+ f'{airline:>15s} {flight_number:<7s} {f["Class"]} '
2023-09-11 06:39:19 +01:00
+ f'{f["Seat"]:>4s} '
+ f'{f["Registration"]:6s} '
+ f'{f["Plane"]} '
2023-09-09 19:50:41 +01:00
)
def read_flights(filename: str) -> Flights:
"""Read flights from CSV."""
reader = csv.DictReader(open(filename))
flights = []
for row in reader:
d = row.pop("\ufeffDate")
if len(d) > 10:
d = datetime.strptime(d, "%Y-%m-%d %H:%M:%S")
else:
d = datetime.strptime(d, "%Y-%m-%d")
row = {k: v for k, v in row.items() if not k.endswith("OID")}
# for key in "Trip", "Seat", "Seat_Type", "Class", "Reason", "Note":
# row.pop(key)
if d < since_date:
continue
flights.append((d, row))
flights.sort()
return flights
def show_flights(flights: Flights) -> None:
"""Show list of flights."""
for d, row in flights:
print(format_row(d, row))
if __name__ == "__main__":
2023-09-11 06:41:07 +01:00
filename = get_most_recent(backup_loc, lambda f: f.endswith(".csv"))
assert filename
2023-09-09 19:50:41 +01:00
flights = read_flights(filename)
show_flights(flights)