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
Thetif1.utils module is a set of helpers for analysis code, compatible with fastf1.utils. It provides four primary categories of functionality:
- Time Conversion Functions: Convert between various time representations (strings, floats, timedeltas, timestamps)
- Performance Analysis Functions: Calculate lap-by-lap deltas and performance metrics
- Data Access Helpers: Safely navigate nested data structures
- FastF1 Compatibility: Maintain API compatibility with the FastF1 library
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
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"
- Short format:
intorfloat: Interpreted as seconds (for example,83.456→ 1 minute 23.456 seconds)numpy.float64: Interpreted as seconds (a subclass offloat)- Any other pandas-compatible time format
Returns
pd.Timedelta: A pandas Timedelta object representing the time duration. Adatetime.timedeltainput is returned unchanged.
Behavior Details
The function implements automatic format detection:- Passthrough for timedelta: If the input is already a
datetime.timedelta, it is returned immediately without conversion overhead - 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
- If exactly one colon is found (for example,
- Numeric conversion: Integer and float inputs are treated as seconds and converted using pandas’ optimized
to_timedelta(x, unit="s") - 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
NonegiveNaT; an unparseable string such as"garbage"raisesValueError(pandas behavior) - Short strings in a Series: A Series of
"m:ss.sss"strings raisesValueError. Use.apply(to_timedelta)for such a Series, andpd.to_timedelta(s, unit="s")for a Series of seconds
Examples
Basic conversions:Common Use Cases
- Lap time analysis: Converting lap times from API responses or CSV files
- Sector time calculations: Normalizing sector times for comparison
- Session time tracking: Converting elapsed session time to timedelta format
- Time gap calculations: Preparing time values for arithmetic operations
- Data import: Standardizing time formats from external data sources
- 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].
to_datetime
Parameters
x(Any): Datetime value in any of the following formats:str: ISO 8601 format ("2025-05-25T14:00:00Z") or other common datetime stringsdatetime.datetime: Python datetime objectsintorfloat: Nanoseconds since the epoch (pandas default), not Unix seconds.to_datetimehas nounitargument; usepd.to_datetime(x, unit="s")for Unix secondspd.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:
- Automatic format detection: Pandas detects ISO 8601, RFC 3339, and common datetime string formats
- Numeric input: Numbers are read as nanoseconds since the epoch
- Timezone awareness: Preserves timezone information when present in the input
- Output type: A scalar input gives a pandas Timestamp (
NaTforNone). A list gives aDatetimeIndex
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;NonegivesNaT
Examples
Basic conversions:Common Use Cases
- Session timing: Converting session start/end times from API responses
- Lap timestamps: Parsing
LapStartDatefields in lap data - Race control messages: Converting message timestamps to datetime objects
- Data synchronization: Aligning data from multiple sources by timestamp
- Time-based filtering: Creating datetime-based queries and filters
- 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
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(Lapor telemetry DataFrame): The baseline lap- A
Lapfromlaps.pick_fastest()ordriver.get_lap(n), or a telemetry frame withTimeandDistance - Telemetry is fetched through
get_car_data()(Polars frames are converted to pandas)
- A
-
compare_lap(Lapor telemetry DataFrame): The lap to compare against the reference- Accepts the same kinds of input as
reference_lap
- Accepts the same kinds of input as
Returns
A tuple containing three elements:-
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/Distancecolumns
-
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; plotdeltaagainstreference_telemetry["Distance"]
- Contains all telemetry channels:
-
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:- Telemetry Retrieval: Gets the telemetry of both laps with
get_car_data()(addsDistancefromSpeedif it is missing) - Time in Seconds: Converts both
Timechannels to float seconds - Distance Alignment: Linearly interpolates (
np.interp) the compare-lap time at each referenceDistance - Delta Calculation: Subtracts the reference time from the interpolated compare time
- 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
Distancechannel
Examples
Basic delta time comparison:Common Use Cases
- Qualifying analysis: Compare fastest laps between teammates or rivals
- Race pace comparison: Analyze lap-by-lap performance during race stints
- Setup evaluation: Compare laps before and after setup changes
- Driver coaching: Identify specific corners where time is lost
- Strategy analysis: Understand tire degradation effects on lap time
- 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
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
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 valueFalse(default): Returns empty dict{}when key path not foundTrue: ReturnsNonewhen 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: ReturnsNone
Behavior Details
The function traverses the dictionary iteratively:- Start with root: Begins with the input dictionary
d - Apply each key: For each key in
*keys, tries to accessd[key] - Handle missing keys: If
KeyErrororTypeErroroccurs, returns the default value - Return final value: If all keys exist, returns the value at the final key
KeyError: Raised when a key does not exist in the dictionaryTypeError: 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
KeyErrorandTypeError; an out-of-range list index still raisesIndexError - Efficient: Short-circuits on first missing key
Examples
Basic nested access:Common Use Cases
- API response parsing: Safely extract data from JSON responses without try-except blocks
- Configuration files: Access nested configuration values with defaults
- Data validation: Check for presence of required fields in nested structures
- ETL pipelines: Extract data from complex nested sources
- Error handling: Gracefully handle missing or malformed data
- 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 usedefault_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
orsupplies fallback values - When data structures are built incrementally
default_none=True:
- When the code must distinguish between “missing” and “empty”
- For explicit
Nonechecks withis 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.
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 usingrecursive_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:
-
Vectorized operations: When converting entire DataFrame columns, use pandas’ native functions directly:
-
Batch processing: Convert data in batches rather than one-by-one:
-
Type checking: Avoid unnecessary conversions by checking types first:
Delta Time Performance
delta_time optimization strategies:
-
Cache telemetry data: If comparing multiple laps, get the reference telemetry once and pass the frame:
-
Limit telemetry channels: When only specific channels are needed, filter after retrieval:
-
Parallel processing: For multiple comparisons, use parallel processing:
Nested Data Access Performance
recursive_dict_get best practices:
-
Minimize depth: Access data at the shallowest level possible:
-
Cache intermediate results: Store frequently accessed nested objects:
-
Use default_none appropriately: Choose the default that fits the use case:
Memory Management
Tips for working with large datasets:-
Process in chunks: For very large lap datasets, process in chunks:
-
Delete unused data: Free memory by deleting intermediate results:
-
Use appropriate data types: Convert to efficient types after processing:
Error Handling Best Practices
Reliable error handling patterns:-
Validate inputs before conversion:
-
Handle missing telemetry gracefully:
-
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 thatto_timedeltacannot convertTypeError: An object thatto_datetimecannot convertIndexError: An out-of-range list index inrecursive_dict_get- No error from
delta_time: An object without telemetry gives an empty delta Series
Integration with tif1 Ecosystem
Use Inside tif1
Thetif1.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_timedeltaorto_datetime - Charts such as
tif1.plot_lap_delta()compute their own values and do not calldelta_time - Payload parsing reads JSON with
orjsonand does not userecursive_dict_get
FastF1 Compatibility
The four functions have the same names and arguments as infastf1.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
delta_time returns empty Series
recursive_dict_get returns empty dict unexpectedly
Related Documentation
Core APIs
- Core API: Main data structures and session loading
- Models API: Lap, Driver, and Telemetry classes
Analysis Tools
- Plotting API: Visualization functions using utilities
Data Types
- Types API: Type definitions for utility functions
- Schedule API: Event scheduling and calendar
Concepts
- Data Flow: Understanding data processing pipeline
- Caching Strategy: Performance optimization
Additional Resources
Support
- GitHub Issues: Report bugs or request features
- Discussions: Ask questions and share examples
- Documentation: Full API documentation