DEV Community

Hanieh Khanmohamad
Hanieh Khanmohamad

Posted on

Build a Time-Zone-Safe Itinerary Validator in Python

A travel itinerary looks like a sequence of cards: a museum at 10:00, lunch at 12:30, and a train later in the day. Underneath those cards, however, is a scheduling problem. Time zones, daylight-saving transitions, inconsistent supplier data, and missing transfer time can make a plan impossible even when every individual booking is valid.

This tutorial builds a small, dependency-free itinerary validator in Python. It will not invent journey durations or decide whether a restaurant is open. Instead, it will check the facts a travel application already has, report conflicts, and explain why a proposed schedule needs attention.

  1. Store instants, not just clock labels Imagine an itinerary containing these two values:
  2. Flight arrival: 14:10
  3. Hotel check-in: 14:45 The 35-minute gap seems clear until you ask which time zone each value uses. The labels might refer to different cities, or a supplier might have stripped the UTC offset. A scheduling engine should not guess.

Require an ISO 8601 timestamp that includes an explicit offset, such as 2027-04-07T10:00:00+02:00. This identifies a real instant. Keep the IANA time-zone name (Europe/Paris, for example) as separate metadata for display and future date calculations.

An offset and a time zone are not interchangeable. Paris is not always UTC+02:00. Its offset changes seasonally. For recurring events or future local-time creation, a time-zone database is essential.

  1. Define a minimal event contract Our prototype uses three event fields and two planning fields:
  2. start and end: offset-aware timestamps
  3. label: a human-readable activity name
  4. travel_after_min: the estimated transfer time required after this event
  5. zone: the IANA time zone used by the activity's local clock The transfer estimate must come from a routing provider, a tour operator, or a clearly labeled user assumption. A validator should never quietly substitute a made-up travel duration. from dataclasses import dataclass from datetime import datetime, timezone from zoneinfo import ZoneInfo

@dataclass(frozen=True)
class Event:
label: str
start: str
end: str
zone: str
travel_after_min: int = 0

def parse_instant(value: str, zone: str) -> datetime:
dt = datetime.fromisoformat(value)
if dt.tzinfo is None or dt.utcoffset() is None:
raise ValueError(f"Missing UTC offset: {value}")

# Reject an offset that disagrees with the named local time zone.
local = dt.astimezone(ZoneInfo(zone))
if local.replace(tzinfo=None) != dt.replace(tzinfo=None):
    raise ValueError(f"Local time/zone mismatch: {value} / {zone}")
if local.utcoffset() != dt.utcoffset():
    raise ValueError(f"UTC offset/zone mismatch: {value} / {zone}")

return dt.astimezone(timezone.utc)
Enter fullscreen mode Exit fullscreen mode

A useful property of this contract is that both the original local time and the absolute instant survive. It also catches one common data error: a summer timestamp labeled with an impossible winter offset for its city. The zoneinfo module uses an IANA time-zone database available to the Python runtime; some environments require installing system time-zone data or the tzdata package.

  1. Check durations, overlaps, and transfer buffers
    An event can be valid in isolation while making the overall plan impossible. Two 90-minute attractions may overlap; a transfer could require 30 minutes while the itinerary provides only 15.
    def validate_itinerary(events: list[Event]) -> list[str]:
    issues = []
    normalized = []

    for event in events:
    start = parse_instant(event.start, event.zone)
    end = parse_instant(event.end, event.zone)

    if end <= start:
        issues.append(f"{event.label}: end must be after start")
    if event.travel_after_min < 0:
        issues.append(f"{event.label}: negative transfer estimate")
    
    normalized.append((start, end, event))
    

    Sorting by UTC avoids incorrect comparisons across time zones.

    normalized.sort(key=lambda item: item[0])

    for previous, current in zip(normalized, normalized[1:]):
    _, previous_end, old = previous
    current_start, _, new = current
    gap_min = (current_start - previous_end).total_seconds() / 60

    if gap_min < 0:
        issues.append(
            f"{old.label} overlaps {new.label} by {-gap_min:g} min"
        )
    elif gap_min < old.travel_after_min:
        issues.append(
            f"{old.label} -> {new.label}: {gap_min:g} min available; "
            f"{old.travel_after_min} min transfer required"
        )
    

    return issues
    This approach is intentionally strict: a missing UTC offset raises an error instead of producing a plausible-looking but untrustworthy result. For a production API, convert that exception into a structured validation response that identifies the affected record.

Notice another design choice: the transfer requirement belongs to the preceding event. That is not the only possible data model. A richer route graph would attach transfer estimates to each pair of locations and travel mode, and might represent transfers as their own scheduled events. Our simpler model is sufficient to demonstrate the principle.

  1. Run a small example These example appointments are deliberately fictional; they are not live opening hours, reservations, or walking-time estimates. plan = [ Event( label="Museum visit", start="2027-04-07T10:00:00+02:00", end="2027-04-07T11:30:00+02:00", zone="Europe/Paris", travel_after_min=45, ), Event( label="Lunch", start="2027-04-07T12:30:00+02:00", end="2027-04-07T13:30:00+02:00", zone="Europe/Paris", travel_after_min=20, ), Event( label="Afternoon walk", start="2027-04-07T13:45:00+02:00", end="2027-04-07T14:30:00+02:00", zone="Europe/Paris", ), ]

for issue in validate_itinerary(plan):
print(issue)
The first interval provides 60 minutes for a 45-minute transfer, so it passes. The second provides 15 minutes for a transfer estimated at 20 minutes, so the script reports:
Lunch -> Afternoon walk: 15 min available; 20 min transfer required
This is an explanation, not a mysterious red warning icon. It tells a traveler or trip planner which assumption has failed.

  1. Prove the validator catches time-zone mistakes Unit tests are more valuable than screenshots of a calendar. Start with two focused checks: an impossible offset and a missing transfer buffer. def test_mismatched_paris_offset(): try: parse_instant("2027-07-10T09:00:00+01:00", "Europe/Paris") except ValueError: pass else: raise AssertionError("Expected a time-zone mismatch")

def test_transfer_conflict():
result = validate_itinerary(plan)
assert len(result) == 1
assert "15 min available" in result[0]

test_mismatched_paris_offset()
test_transfer_conflict()
For production, also test overnight activities, invalid IANA zones, clock changes, duplicate reservations, canceled events, and departure/arrival records across different countries. During a daylight-saving fall-back, the same wall-clock time can occur twice. Requiring a timestamp with an explicit offset helps disambiguate the instant, but you should still test it against the named zone.

  1. Separate validation from optimization A validator answers: Is this itinerary internally consistent under the supplied assumptions? An optimizer answers: Can we find a better itinerary? Those are different responsibilities.

A robust architecture can use a pipeline:

  1. Ingest: collect opening hours, reservations, transit details, and user preferences from their original sources.
  2. Normalize: preserve source identifiers, local times, offsets, zone names, and update timestamps.
  3. Validate: reject malformed events and flag impossible transfers or overlaps.
  4. Optimize: suggest alternative ordering or times only after validation succeeds.
  5. Present: distinguish verified facts from estimates and clearly label unresolved conflicts. If a provider changes a departure time, the itinerary should be revalidated before new recommendations appear. Never silently convert a 45-minute transfer estimate into a 10-minute one just to make the schedule fit.
  6. A practical data provenance checklist Travel products often combine supplier feeds, map routing, editorial destination guides, and user-created notes. Treating all four as equally authoritative is a recipe for misleading plans. A small provenance record can prevent this: { "field": "travel_after_min", "value": 45, "source_type": "user_estimate", "verified": false, "recorded_at": "2026-11-26T14:00:00Z" } In a live service, this metadata lets the interface say "45-minute transfer, estimated by traveler" rather than displaying the duration as a confirmed routing calculation. The same pattern is useful for attraction hours and seasonal restrictions. If information is stale, make that visible before a customer purchases a ticket.

For Persian-language destination context and the broader travel-and-tourism ecosystem, Gashtanio publishes related material for readers exploring places and travel choices. The engineering principle remains universal: reliable itineraries should make their assumptions inspectable.

  1. What to build next This sample is deliberately not a route planner. It does not geocode locations, calculate road or rail journey times, check tickets, or query real-time availability. Those should arrive through dedicated services with explicit provenance and error handling.

A useful next iteration would introduce an itinerary_version, store the validation result with its data-source revisions, and rerun checks whenever a supplier changes a reservation. Another extension would distinguish hard constraints (a booked flight) from soft preferences (a preferred lunch time).

The goal is not to build a perfect vacation app in one Python file. It is to make a very common class of scheduling error measurable and explainable before it reaches a traveler.
Disclosure: This educational article was drafted with AI assistance. The examples use fictional itinerary data and should be tested against real requirements before production deployment. Gashtanio is an affiliated publication mentioned for contextual reading.

Top comments (0)