Skip to main content

Python Interface to Travel Time.

Project description

TravelTime Python SDK

PyPI version Unit Tests Python support

The TravelTime Python SDK provides a simple and efficient way to access the TravelTime API, enabling you to calculate travel times and distances, generate isochrones, and perform location-based queries using real-world transportation data.

Features

  • Time Matrix & Filtering: Calculate travel times between multiple origins and destinations
  • Isochrone Generation: Create time-based catchment areas in multiple formats (GeoJSON, WKT)
  • Route Planning: Get detailed turn-by-turn directions between locations
  • Geocoding: Convert addresses to coordinates and vice versa
  • Specialized Analysis: UK postcode analysis, H3 hexagon analysis, and geohash analysis
  • Transportation Modes: Support for driving, public transport, walking, cycling, and multimodal transport
  • Async Support: Both synchronous and asynchronous clients available
  • Performance Options: Fast endpoints for high-volume use cases

Requirements

  • Python 3.10 or higher

To check your Python version:

python --version

Installation

Install the TravelTime Python SDK using pip:

pip install traveltimepy

Optional Dependencies

For protocol buffer (protobuf) support (required for TimeFilterFastProto endpoints):

pip install 'traveltimepy[proto]'

Getting Started

Authentication

Get your API credentials from the TravelTime Developer Portal.

Basic Usage

from datetime import datetime
from traveltimepy import Client
from traveltimepy.requests.common import Location, Coordinates, Property
from traveltimepy.requests.time_filter import TimeFilterDepartureSearch
from traveltimepy.requests.transportation import PublicTransport
from traveltimepy.errors import TravelTimeApiError

# Define locations
locations = [
    Location(id="London center", coords=Coordinates(lat=51.508930, lng=-0.131387)),
    Location(id="Hyde Park", coords=Coordinates(lat=51.508824, lng=-0.167093)),
    Location(id="ZSL London Zoo", coords=Coordinates(lat=51.536067, lng=-0.153596))
]

# Option 1: Standard usage (manual session management)
client = Client(app_id="YOUR_APP_ID", api_key="YOUR_API_KEY")

try:
    response = client.time_filter(
        locations=locations,
        departure_searches=[
            TimeFilterDepartureSearch(
                id="London center",
                departure_location_id="London center", 
                arrival_location_ids=["Hyde Park", "ZSL London Zoo"],
                departure_time=datetime.now(),
                transportation=PublicTransport(),
                travel_time=1800,  # 30 minutes
                properties=[Property.TRAVEL_TIME]
            )
        ],
        arrival_searches=[]
    )
    
    print(f"Found {len(response.results)} results")
    for result in response.results:
        print(f"Search ID: {result.search_id}")
            
except TravelTimeApiError as e:
    print(e)
finally:
    client.close()  # Manually close session

# Option 2: Context manager (automatic session cleanup)
with Client(app_id="YOUR_APP_ID", api_key="YOUR_API_KEY") as client:
    try:
        response = client.time_filter(
            locations=locations,
            departure_searches=[
                TimeFilterDepartureSearch(
                    id="London center",
                    departure_location_id="London center", 
                    arrival_location_ids=["Hyde Park", "ZSL London Zoo"],
                    departure_time=datetime.now(),
                    transportation=PublicTransport(),
                    travel_time=1800,
                    properties=[Property.TRAVEL_TIME]
                )
            ],
            arrival_searches=[]
        )
        
        print(f"Found {len(response.results)} results")
        for result in response.results:
            print(f"Search ID: {result.search_id}")
            
    except TravelTimeApiError as e:
        print(e)
    # Session automatically closed when exiting 'with' block

Async Usage

import asyncio
from datetime import datetime
from traveltimepy import AsyncClient
from traveltimepy.requests.common import Location, Coordinates
from traveltimepy.requests.time_filter import TimeFilterDepartureSearch
from traveltimepy.requests.transportation import PublicTransport
from traveltimepy.errors import TravelTimeApiError

locations = [
    Location(id="London center", coords=Coordinates(lat=51.508930, lng=-0.131387)),
    Location(id="Hyde Park", coords=Coordinates(lat=51.508824, lng=-0.167093)),
    Location(id="ZSL London Zoo", coords=Coordinates(lat=51.536067, lng=-0.153596))
]

# Option 1: Standard async usage (manual session management)
async def main():
    client = AsyncClient(app_id="YOUR_APP_ID", api_key="YOUR_API_KEY")
    
    try:
        response = await client.time_filter(
            locations=locations,
            departure_searches=[
                TimeFilterDepartureSearch(
                    id="London center",
                    departure_location_id="London center",
                    arrival_location_ids=["Hyde Park", "ZSL London Zoo"],
                    departure_time=datetime.now(),
                    transportation=PublicTransport(),
                    travel_time=1800
                )
            ],
            arrival_searches=[]
        )
        
        print(f"Found {len(response.results)} results")
        for result in response.results:
            print(f"Search ID: {result.search_id}")
            
    except TravelTimeApiError as e:
        print(e)
    finally:
        await client.close()  # Manually close session

# Option 2: Async context manager (automatic session cleanup)
async def main_with_context():
    async with AsyncClient(app_id="YOUR_APP_ID", api_key="YOUR_API_KEY") as client:
        try:
            response = await client.time_filter(
                locations=locations,
                departure_searches=[
                    TimeFilterDepartureSearch(
                        id="London center",
                        departure_location_id="London center",
                        arrival_location_ids=["Hyde Park", "ZSL London Zoo"],
                        departure_time=datetime.now(),
                        transportation=PublicTransport(),
                        travel_time=1800
                    )
                ],
                arrival_searches=[]
            )
            
            print(f"Found {len(response.results)} results")
            for result in response.results:
                print(f"Search ID: {result.search_id}")
                
        except TravelTimeApiError as e:
            print(e)
        # Session automatically closed when exiting 'async with' block

# Run either version
asyncio.run(main())
# or
asyncio.run(main_with_context())

Core Methods

The SDK provides both synchronous (Client) and asynchronous (AsyncClient) versions of all methods:

Time Matrix & Filtering

Isochrone Generation

Route Planning

  • routes() - Calculate detailed routes between locations

Geocoding

Specialized Analysis

Utility Methods

Configuration

The SDK supports various configuration options:

from traveltimepy import Client, AsyncClient

# Synchronous client
client = Client(
    app_id="YOUR_APP_ID",
    api_key="YOUR_API_KEY",
    timeout=300,                    # Request timeout in seconds
    retry_attempts=3,               # Number of retry attempts for 5xx errors
    max_rpm=60,                     # Maximum requests per minute
)

# Asynchronous client
async_client = AsyncClient(
    app_id="YOUR_APP_ID",
    api_key="YOUR_API_KEY",
    timeout=300,
    retry_attempts=3,
    max_rpm=60
)

Error Handling and Retries

The SDK automatically handles both rate limiting and server error retries:

  • Rate limiting: Automatically handled with exponential backoff
  • Server errors (5xx): Automatically retried up to 3 times with immediate retry
  • Client errors (4xx): Not retried (indicates invalid request)
# Retries are built-in - no additional code needed
client = Client(app_id="YOUR_APP_ID", api_key="YOUR_API_KEY")
response = client.time_filter(
    locations=locations,
    departure_searches=searches
)  # Automatically retries on 5xx errors

Configuring Retries

You can configure the number of retry attempts:

# Custom retry attempts
client = Client(
    app_id="YOUR_APP_ID", 
    api_key="YOUR_API_KEY",
    retry_attempts=5  # Will retry up to 5 times on 5xx errors
)

# Disable retries completely
client = Client(
    app_id="YOUR_APP_ID", 
    api_key="YOUR_API_KEY",
    retry_attempts=0  # No retries, fail immediately
)

Examples

The examples/ directory contains practical examples. See examples/README.md for setup instructions and detailed descriptions.

Performance Tips

  • Use *_fast() methods for high-volume use cases
  • Use time_filter_proto() and geohash_fast_proto() for maximum performance with large datasets (install with pip install 'traveltimepy[proto]')
  • Use async methods for I/O-bound applications

Documentation

For comprehensive documentation, including detailed parameter references and advanced usage examples, visit:

Support

If you have questions or need help:

License

This project is licensed under the MIT License - see the LICENSE file for details.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

traveltimepy-4.6.0.tar.gz (76.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

traveltimepy-4.6.0-py3-none-any.whl (114.7 kB view details)

Uploaded Python 3

File details

Details for the file traveltimepy-4.6.0.tar.gz.

File metadata

  • Download URL: traveltimepy-4.6.0.tar.gz
  • Upload date:
  • Size: 76.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.20

File hashes

Hashes for traveltimepy-4.6.0.tar.gz
Algorithm Hash digest
SHA256 bbb0d5e3e3fd4b7061501c870db58017a0242cd1f588cf9f25dfd526bf74964f
MD5 b78e13d6bdf0fa94da7c11dee9c5fd4d
BLAKE2b-256 c33bf6f9d4b98617dfe147371a932dc97da8d36fd1a56bcaf732321a75e101b0

See more details on using hashes here.

File details

Details for the file traveltimepy-4.6.0-py3-none-any.whl.

File metadata

  • Download URL: traveltimepy-4.6.0-py3-none-any.whl
  • Upload date:
  • Size: 114.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.20

File hashes

Hashes for traveltimepy-4.6.0-py3-none-any.whl
Algorithm Hash digest
SHA256 56eb3563a103558299a8e8326b419e86e9ece1e7940e4e1397bd3de43bbcc1f9
MD5 a4c686963450d536ac67377430300a5f
BLAKE2b-256 f083e757a0f5d54f12b42f92d3f242c904b9469fab4b593150be7c42892c831d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page