Skip to main content

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, optionally with the H3 cells each route passes through

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 and connection failures
    rate_limit_retry_attempts=4,    # Number of retry attempts for 429 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,
    rate_limit_retry_attempts=4,
    max_rpm=60
)

Error Handling and Retries

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

  • Rate limiting (429): Retried up to 4 times, about 30 seconds apart
  • Server errors (5xx) and connection failures: Retried up to 3 times with exponential backoff (1s, 2s, 4s)
  • Timeouts and client errors (4xx): Not retried
# 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 429, 5xx and connection 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 and connection errors
    rate_limit_retry_attempts=10  # Will retry up to 10 times on 429 errors
)

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

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(), h3_fast_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.

Metadata

Release files for traveltimepy 4.11.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for traveltimepy 4.11.0
File Size Uploaded Provenance Actions
traveltimepy-4.11.0.tar.gz 84.5 kB Without provenance Details for traveltimepy-4.11.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for traveltimepy 4.11.0
File Interpreter ABI Platform Actions
traveltimepy-4.11.0-py3-none-any.whl Python 3 none any Details for traveltimepy-4.11.0-py3-none-any.whl

Total release size: 175.4 kB

Release files / traveltimepy-4.11.0.tar.gz

Download URL traveltimepy-4.11.0.tar.gz
Size 84.5 kB
Tags Source
SHA-256 checksum
How to use checksums
25d96d55c5dbf2208e967fe106d1f007f148cf65f006b0f31ca1a02934257264
BLAKE2b-256 checksum
How to use checksums
e70ee241accd1affd24fd647456e5cfef9789e7cc607d786f731c6622b91257d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.22

Release files / traveltimepy-4.11.0-py3-none-any.whl

Download URL traveltimepy-4.11.0-py3-none-any.whl
Size 90.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
92c3b0b845f0a59ea9ca835ee6cd84a8bb92fd92bf2823523d2884435219dcff
BLAKE2b-256 checksum
How to use checksums
926cab1714f67d023e6fa01c9ce11765582dcc7de85f4d7bf28920cb6015b6a0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.22

Security for traveltimepy 4.11.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

4.11.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page