Improvements

This commit is contained in:
Edward Betts 2023-09-09 21:50:41 +03:00
commit 1f8626d76b

85
show Executable file
View file

@ -0,0 +1,85 @@
#!/usr/bin/python3
import csv
from datetime import datetime, timedelta
# from pprint import pprint
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]]
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"]} '
+ f'{f["Seat"]:>4s} {f["Plane"]}'
)
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__":
filename = "/home/edward/backup/openflights/openflights-backup-2023-09-09.csv"
flights = read_flights(filename)
show_flights(flights)