time calculation
time interval
programming
datetime
string manipulation

How to calculate the time interval between two time strings

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Calculating the interval between two time strings is easy only when you know exactly what the strings mean. The result depends on format, whether the times belong to the same day, and whether crossing midnight should count as a negative interval or as "next day" behavior.

Parse First, Then Subtract

The correct pattern is:

  1. parse both strings into time or datetime objects
  2. normalize them into the same reference frame
  3. subtract them
  4. decide how to handle negative results or overnight rollover

If you subtract raw strings or integers built from string fragments, edge cases appear quickly.

Example in Python

For same-day 24-hour times, Python’s datetime module is a good default:

python
1from datetime import datetime
2
3start = datetime.strptime("09:15", "%H:%M")
4end = datetime.strptime("13:45", "%H:%M")
5interval = end - start
6
7print(interval)
8print(interval.total_seconds() / 60)

This prints a timedelta representing 4 hours and 30 minutes.

Handling Overnight Intervals

One of the most common pitfalls is a range such as 23:30 to 01:15. If you parse both as the same date, subtraction gives a negative duration. In many scheduling problems, the intended meaning is that the end time belongs to the next day.

Here is a simple way to support that:

python
1from datetime import datetime, timedelta
2
3
4def interval_between(start_str, end_str):
5    start = datetime.strptime(start_str, "%H:%M")
6    end = datetime.strptime(end_str, "%H:%M")
7
8    if end < start:
9        end += timedelta(days=1)
10
11    return end - start
12
13
14print(interval_between("23:30", "01:15"))

This returns 1 hour and 45 minutes instead of a negative value.

When You Need Full Datetimes

If the strings include dates or timestamps, work with full datetime values instead of stripping down to time-of-day only. That avoids ambiguity and makes timezone handling possible.

Example:

python
1from datetime import datetime
2
3start = datetime.fromisoformat("2025-09-24T23:30:00")
4end = datetime.fromisoformat("2025-09-25T01:15:00")
5
6print(end - start)

When real dates exist, do not throw them away and then try to reconstruct the interval manually.

Time Zones Matter

If the strings represent local times in different zones, or timestamps that include offsets, you must preserve timezone information. Otherwise, the interval can be off by hours.

For ISO 8601 strings with offsets, use timezone-aware parsing and subtraction so the library handles the conversion for you.

The core rule is simple: subtract like from like.

Choosing the Output Unit

The raw result is often a timedelta, but applications usually want a specific unit:

  • seconds for low-level systems
  • minutes for schedules
  • decimal hours for reporting
  • hours and minutes for display

Example conversion:

python
1interval = interval_between("09:15", "13:45")
2minutes = interval.total_seconds() / 60
3hours = interval.total_seconds() / 3600
4
5print(minutes)
6print(hours)

Keep the interval as a duration object as long as possible, and convert to presentation units at the edge.

Format Validation

If the input format is not guaranteed, validate it early and fail clearly. Silent parsing assumptions create subtle bugs.

For example, 02:30 could mean 2:30 AM in 24-hour time, but 02:30 PM belongs to a different parsing rule entirely. Mixing formats in the same code path without validation is a frequent source of errors.

Common Pitfalls

The biggest mistake is ignoring overnight rollover. A negative interval is sometimes correct, but in scheduling systems it often means you forgot to handle next-day logic.

Another issue is using time-of-day values when full dates are available. That throws away information you actually need.

Developers also often forget time zones. Two timestamps that look similar as strings may represent different absolute moments.

Finally, do not convert durations to integers too early. Keep a proper duration object until you are ready to format the result.

Summary

  • Parse time strings into real date or time objects before subtracting.
  • Decide explicitly whether crossing midnight should produce a negative interval or a next-day interval.
  • Use full datetimes when date information exists.
  • Preserve timezone information when timestamps include offsets or come from different zones.
  • Keep the result as a duration object until the final formatting step.

Course illustration
Course illustration

All Rights Reserved.