Skip to main content
The utils module provides a suite of utility functions designed to simplify working with Formula 1 data. These functions handle common tasks such as time format conversions, lap-by-lap performance comparisons, and safe nested data access.

Overview

The tif1.utils module is a set of helpers for analysis code, compatible with fastf1.utils. It provides four primary categories of functionality:
  1. Time Conversion Functions: Convert between various time representations (strings, floats, timedeltas, timestamps)
  2. Performance Analysis Functions: Calculate lap-by-lap deltas and performance metrics
  3. Data Access Helpers: Safely navigate nested data structures
  4. FastF1 Compatibility: Maintain API compatibility with the FastF1 library
Session loading does not use these helpers: tif1 builds its time columns with vectorized pandas or Polars code. Use the helpers on custom data, such as timing strings from a CSV file.
recursive_dict_get and delta_time return defaults ({}, None or an empty Series) instead of raising. to_timedelta and to_datetime raise the pandas error for input that pandas cannot parse.

Time Conversion Functions

Time conversion is a critical part of working with Formula 1 data. Timing information arrives in multiple formats. These formats include ISO strings from the API, numeric seconds from telemetry, and formatted strings from timing screens. The utilities module provides converters that handle all these formats.

to_timedelta

Converts various time representations to a standardized pandas Timedelta object. Use it for single lap, sector, or session time values in custom data.

Parameters

  • x (Any): Time value in any of the following formats:
    • datetime.timedelta: Returned unchanged (passthrough)
    • str: Parsed as a time string with automatic format detection
      • Short format: "1:23.456" (minutes:seconds.milliseconds) → automatically prepended with "00:" to become "00:01:23.456"
      • Full format: "00:01:23.456" (hours:minutes:seconds.milliseconds)
      • ISO 8601 duration format: "PT1M23.456S"
    • int or float: Interpreted as seconds (for example, 83.456 → 1 minute 23.456 seconds)
    • numpy.float64: Interpreted as seconds (a subclass of float)
    • Any other pandas-compatible time format
A numpy.integer or numpy.float32 value is not an int or float subclass, so pd.to_timedelta() reads it as nanoseconds. For example, to_timedelta(np.int64(90)) gives 90 ns. Convert the value with int() or float() first.

Returns

  • pd.Timedelta: A pandas Timedelta object representing the time duration. A datetime.timedelta input is returned unchanged.

Behavior Details

The function implements automatic format detection:
  1. Passthrough for timedelta: If the input is already a datetime.timedelta, it is returned immediately without conversion overhead
  2. String parsing with auto-formatting: String inputs are analyzed for colon count:
    • If exactly one colon is found (for example, "1:23.456"), the function prepends "00:" to create a valid hours:minutes:seconds format
    • This allows users to input lap times naturally without typing leading zeros
  3. Numeric conversion: Integer and float inputs are treated as seconds and converted using pandas’ optimized to_timedelta(x, unit="s")
  4. Fallback to pandas: Any other format is passed directly to pd.to_timedelta() for pandas’ native parsing

Performance Characteristics

  • O(1) complexity for all input types
  • Zero-copy for timedelta passthrough
  • Scalars, not Series: A pandas Series goes straight to pd.to_timedelta() without a unit, so numbers become nanoseconds
  • Errors: Empty strings and None give NaT; an unparseable string such as "garbage" raises ValueError (pandas behavior)
  • Short strings in a Series: A Series of "m:ss.sss" strings raises ValueError. Use .apply(to_timedelta) for such a Series, and pd.to_timedelta(s, unit="s") for a Series of seconds

Examples

Basic conversions:
Working with lap data:
Vectorized operations with pandas:
Handling edge cases:

Common Use Cases

  1. Lap time analysis: Converting lap times from API responses or CSV files
  2. Sector time calculations: Normalizing sector times for comparison
  3. Session time tracking: Converting elapsed session time to timedelta format
  4. Time gap calculations: Preparing time values for arithmetic operations
  5. Data import: Standardizing time formats from external data sources
  6. FastF1 compatibility: Maintaining API compatibility when migrating from FastF1

Integration with tif1

tif1 does not call to_timedelta internally. The function exists for code ported from fastf1.utils. Session loading builds the time columns (LapTime, Sector1Time, Time, …) with vectorized pandas or Polars operations. On pandas these columns are already timedelta64[ns].
When working with very large datasets, consider using pandas’ native pd.to_timedelta() directly on entire Series for better performance. The to_timedelta utility is optimized for single values and small batches.

to_datetime

Converts various datetime representations to a standardized pandas Timestamp object. Use it for single timestamps in custom data, such as event start times.

Parameters

  • x (Any): Datetime value in any of the following formats:
    • str: ISO 8601 format ("2025-05-25T14:00:00Z") or other common datetime strings
    • datetime.datetime: Python datetime objects
    • int or float: Nanoseconds since the epoch (pandas default), not Unix seconds. to_datetime has no unit argument; use pd.to_datetime(x, unit="s") for Unix seconds
    • pd.Timestamp: Pandas Timestamp (passthrough)
    • Any other pandas-compatible datetime format

Returns

  • pd.Timestamp: A pandas Timestamp object representing the datetime

Behavior Details

This function is a thin wrapper around pandas’ pd.to_datetime() function, providing:
  1. Automatic format detection: Pandas detects ISO 8601, RFC 3339, and common datetime string formats
  2. Numeric input: Numbers are read as nanoseconds since the epoch
  3. Timezone awareness: Preserves timezone information when present in the input
  4. Output type: A scalar input gives a pandas Timestamp (NaT for None). A list gives a DatetimeIndex

Performance Characteristics

  • O(1) complexity for all input types
  • Delegates to pandas: Uses pandas’ optimized C-based datetime parsing
  • Timezone-aware: Handles both naive and timezone-aware datetimes
  • Error handling: An unparseable string raises ValueError; None gives NaT

Examples

Basic conversions:
Working with session data:
Working with lap timestamps:
Timezone handling:
Vectorized operations:

Common Use Cases

  1. Session timing: Converting session start/end times from API responses
  2. Lap timestamps: Parsing LapStartDate fields in lap data
  3. Race control messages: Converting message timestamps to datetime objects
  4. Data synchronization: Aligning data from multiple sources by timestamp
  5. Time-based filtering: Creating datetime-based queries and filters
  6. Timezone conversions: Standardizing times across different timezone formats

Integration with tif1

tif1 does not call to_datetime internally. On pandas, LapStartDate (laps) and Time (race control messages) are already datetime64 columns when the session loads.
Unlike to_timedelta which represents durations, to_datetime represents specific points in time. Use to_timedelta for lap times and intervals, and to_datetime for absolute timestamps.

Performance Analysis Functions

Performance analysis is central to Formula 1 data science. The utilities module provides functions to compare lap performance and calculate time deltas. These functions identify where drivers gain or lose time on track.

delta_time

Estimates the time delta between two laps at each telemetry sample of the reference lap. The algorithm follows fastf1.utils.delta_time, without the distance scaling of recent FastF1 versions (see FastF1 Compatibility). It shows where along the track one lap gains or loses time against the other.

Parameters

  • reference_lap (Lap or telemetry DataFrame): The baseline lap
    • A Lap from laps.pick_fastest() or driver.get_lap(n), or a telemetry frame with Time and Distance
    • Telemetry is fetched through get_car_data() (Polars frames are converted to pandas)
  • compare_lap (Lap or telemetry DataFrame): The lap to compare against the reference
    • Accepts the same kinds of input as reference_lap

Returns

A tuple containing three elements:
  1. delta (pd.Series, float64): Estimated time delta in seconds
    • Index: The index of the reference telemetry (one value per reference sample), not the distance
    • Values: Positive = the compare lap reached that point later (slower); negative = earlier (faster)
    • Empty Series: When either lap has fewer than two samples or no Time/Distance columns
  2. reference_telemetry (pd.DataFrame): Telemetry of the reference lap
    • Contains all telemetry channels: Time, Speed, RPM, nGear, Throttle, Brake, DRS, Distance, etc.
    • Shares its index with delta; plot delta against reference_telemetry["Distance"]
  3. compare_telemetry (pd.DataFrame): Telemetry of the comparison lap, unchanged
    • Same columns as the reference telemetry, but its own index and length (not resampled)

Algorithm Details

The delta time calculation follows these steps:
  1. Telemetry Retrieval: Gets the telemetry of both laps with get_car_data() (adds Distance from Speed if it is missing)
  2. Time in Seconds: Converts both Time channels to float seconds
  3. Distance Alignment: Linearly interpolates (np.interp) the compare-lap time at each reference Distance
  4. Delta Calculation: Subtracts the reference time from the interpolated compare time
The result shows:
  • Positive delta: Compare lap is behind at that point (slower)
  • Negative delta: Compare lap is ahead at that point (faster)
  • Zero delta: Both laps are equal at that point
The delta is an estimate. Distance comes from integrated speed, so small errors add up along the lap. The last delta value can differ from the real lap time gap by a few tenths of a second. For the total gap, subtract the LapTime values.

Performance Characteristics

  • Complexity: O(n + m) linear interpolation over the n reference and m compare samples
  • Memory: Requires the telemetry of both laps (several hundred samples per lap)
  • Interpolation: Uses NumPy linear interpolation
  • Accuracy: Limited by the telemetry sample rate (about 7-9 Hz) and the integrated Distance channel

Examples

Basic delta time comparison:
Visualizing delta time:
Multi-panel analysis with speed traces:
Identifying key performance differences:
Comparing multiple laps:

Common Use Cases

  1. Qualifying analysis: Compare fastest laps between teammates or rivals
  2. Race pace comparison: Analyze lap-by-lap performance during race stints
  3. Setup evaluation: Compare laps before and after setup changes
  4. Driver coaching: Identify specific corners where time is lost
  5. Strategy analysis: Understand tire degradation effects on lap time
  6. Track evolution: Compare laps from different sessions as track improves

Interpretation Guidelines

When analyzing delta time plots:
  • Consistent positive delta: Compare driver is consistently slower (setup or skill gap)
  • Consistent negative delta: Compare driver is consistently faster
  • Oscillating delta: Different driving styles or lines through corners
  • Sharp spikes: Mistakes, traffic, or yellow flags
  • Gradual changes: Tire degradation or fuel load differences
  • Sector-specific patterns: Car strengths/weaknesses in different corner types
Delta time calculations require both laps to have complete telemetry data. Laps with missing telemetry (for example, in-laps, out-laps, or laps with data gaps) may produce inaccurate results.
For the most accurate comparisons, use laps from the same session with similar track conditions, tire compounds, and fuel loads. Comparing laps across different sessions may show misleading deltas due to track evolution.

Data Access Functions

Working with nested JSON data from Formula 1 APIs requires safe navigation through complex data structures. The utilities module provides helper functions to access nested dictionary values without raising exceptions.

recursive_dict_get

Safely accesses nested dictionary values using a sequence of keys. The function returns a default value if any key in the path does not exist. This function eliminates the need for multiple try-except blocks or chained .get() calls.

Parameters

  • d (dict): The dictionary to traverse
    • Can be any nested dictionary structure
    • Typically JSON data from API responses
  • *keys (str): Variable number of keys defining the path to traverse
    • Each key represents one level deeper in the nested structure
    • Keys are applied in order: d[key1][key2][key3]...
    • Can be any number of keys (0 to N)
  • default_none (bool, optional): Controls the default return value
    • False (default): Returns empty dict {} when key path not found
    • True: Returns None when key path not found

Returns

  • Any: The value at the specified key path, or the default value if not found
    • If all keys exist: Returns the value at the final key
    • If any key missing and default_none=False: Returns {}
    • If any key missing and default_none=True: Returns None

Behavior Details

The function traverses the dictionary iteratively:
  1. Start with root: Begins with the input dictionary d
  2. Apply each key: For each key in *keys, tries to access d[key]
  3. Handle missing keys: If KeyError or TypeError occurs, returns the default value
  4. Return final value: If all keys exist, returns the value at the final key
The function handles two types of errors:
  • KeyError: Raised when a key does not exist in the dictionary
  • TypeError: Raised when trying to index a non-dict value (for example, None[key])

Performance Characteristics

  • Complexity: O(n) where n is the number of keys
  • Memory: O(1) - no additional data structures created
  • Safe for dicts: Catches KeyError and TypeError; an out-of-range list index still raises IndexError
  • Efficient: Short-circuits on first missing key

Examples

Basic nested access:
Handling missing keys:
Comparison with traditional approaches:
Working with API responses:
Conditional data processing:
Choosing between default behaviors:

Common Use Cases

  1. API response parsing: Safely extract data from JSON responses without try-except blocks
  2. Configuration files: Access nested configuration values with defaults
  3. Data validation: Check for presence of required fields in nested structures
  4. ETL pipelines: Extract data from complex nested sources
  5. Error handling: Gracefully handle missing or malformed data
  6. Data exploration: Probe unknown data structures without raising exceptions

Integration with tif1

tif1 does not call recursive_dict_get internally. It is a fastf1.utils-compatible helper for parsing custom JSON in user code.

Best Practices

When to use default_none=False (default):
  • When processing must continue even if data is missing
  • When the code iterates over results (empty dict is safe to iterate)
  • When or supplies fallback values
  • When data structures are built incrementally
When to use default_none=True:
  • When the code must distinguish between “missing” and “empty”
  • For explicit None checks with is None
  • When validating required fields
  • When missing data must raise errors
The function returns the default value on the first missing key. It short-circuits and does not traverse the entire key path when an early key is missing.
For deeply nested structures with many optional fields, consider using default_none=True and checking for None explicitly. This makes the intent of the code clearer and helps distinguish missing data from empty values.

Complete Real-World Examples

These examples demonstrate how to combine multiple utility functions to solve real-world Formula 1 data analysis problems.

Example 1: Complete Lap Time Analysis

This example shows how to analyze lap times across an entire session, identifying trends, outliers, and performance patterns.

Example 2: Session Timing and Event Correlation

Analyze session timing to correlate events with lap times and identify patterns.

Example 3: Advanced Delta Time Analysis with Driver Comparison

Perform delta time analysis across multiple drivers and identify performance patterns.

Example 4: Data Pipeline with Safe Nested Access

Build a reliable data processing pipeline using recursive_dict_get for safe data extraction.

Performance Considerations and Best Practices

Understanding the performance characteristics of utility functions helps developers write efficient data analysis code.

Time Conversion Performance

to_timedelta and to_datetime optimization tips:
  1. Vectorized operations: When converting entire DataFrame columns, use pandas’ native functions directly:
  2. Batch processing: Convert data in batches rather than one-by-one:
  3. Type checking: Avoid unnecessary conversions by checking types first:

Delta Time Performance

delta_time optimization strategies:
  1. Cache telemetry data: If comparing multiple laps, get the reference telemetry once and pass the frame:
  2. Limit telemetry channels: When only specific channels are needed, filter after retrieval:
  3. Parallel processing: For multiple comparisons, use parallel processing:

Nested Data Access Performance

recursive_dict_get best practices:
  1. Minimize depth: Access data at the shallowest level possible:
  2. Cache intermediate results: Store frequently accessed nested objects:
  3. Use default_none appropriately: Choose the default that fits the use case:

Memory Management

Tips for working with large datasets:
  1. Process in chunks: For very large lap datasets, process in chunks:
  2. Delete unused data: Free memory by deleting intermediate results:
  3. Use appropriate data types: Convert to efficient types after processing:

Error Handling Best Practices

Reliable error handling patterns:
  1. Validate inputs before conversion:
  2. Handle missing telemetry gracefully:
  3. Validate nested data structure:

API Reference Summary

Function Signatures

Return Types

Common Exceptions

The following errors can occur:
  • ValueError: Invalid input format that pandas cannot parse, or an object that to_timedelta cannot convert
  • TypeError: An object that to_datetime cannot convert
  • IndexError: An out-of-range list index in recursive_dict_get
  • No error from delta_time: An object without telemetry gives an empty delta Series

Integration with tif1 Ecosystem

Use Inside tif1

The tif1.utils module is a compatibility layer for code ported from fastf1.utils. No other tif1 module imports it:
  • Session loading builds the time columns with vectorized pandas or Polars code, not with to_timedelta or to_datetime
  • Charts such as tif1.plot_lap_delta() compute their own values and do not call delta_time
  • Payload parsing reads JSON with orjson and does not use recursive_dict_get
Call the utilities directly in analysis code:

FastF1 Compatibility

The four functions have the same names and arguments as in fastf1.utils. Some edge cases give different results (compared with FastF1 3.8):

Compatible Functions

Migration Example


Troubleshooting

Common Issues and Solutions

Issue: to_timedelta raises ValueError for a lap time string
Issue: delta_time returns empty Series
Issue: recursive_dict_get returns empty dict unexpectedly
Issue: Performance degradation with large datasets

Core APIs

  • Core API: Main data structures and session loading
  • Models API: Lap, Driver, and Telemetry classes

Analysis Tools

Data Types

Concepts


Additional Resources

Support

Use vectorized pandas operations when working with large datasets. Cache intermediate results when performing multiple analyses on the same data.
Last modified on October 15, 2026