Calculate the Flight Time between Two Cities using Python
You may using the following Python script to calculate the flight time between two cities.
You may using the following Python script to calculate the flight time between two cities.
from geopy.geocoders import Nominatim
from geopy.distance import great_circle
import math
def flight_time(origin, destination, speed=885):
# Get the latitude and longitude of the origin and destination cities
geolocator = Nominatim(user_agent="flight-time-calculator")
origin_location = geolocator.geocode(origin)
dest_location = geolocator.geocode(destination)
if not origin_location or not dest_location:
raise ValueError("Unable to geocode origin or destination.")
origin_lat, origin_lon = origin_location.latitude, origin_location.longitude
dest_lat, dest_lon = dest_location.latitude, dest_location.longitude
# Calculate the great circle distance between the origin and destination in km
distance = great_circle((origin_lat, origin_lon), (dest_lat, dest_lon)).kilometers
# Calculate the flight time in hours based on the distance and speed
flight_time = distance / speed
hours = math.floor(flight_time)
minutes = round((flight_time - hours) * 60)
# Return the flight time as a string
return f"{hours}h {minutes}m"
# Example usage
origin = "New York City, NY"
destination = "London, UK"
flight_time = flight_time(origin, destination)
print(f"Flight time from {origin} to {destination}: {flight_time}")
The script assumes that the speed of the airplane is 885, which is on the lower end of the average speed of a commercial airliner, which is 885-965 kilometers per hour. You may change the speed on line five.