Created
April 24, 2026 03:21
-
-
Save brandonhimpfen/6761bcf16cf6c988922924f2d2a7bbd4 to your computer and use it in GitHub Desktop.
Python script to calculate the flight time between two cities.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment