Inferensys

Prompt

Relative Date Normalization Prompt Template

A practical prompt playbook for converting relative time expressions like 'last quarter' or 'recent' into explicit ISO 8601 date ranges for retrieval systems.
Developer building agentic RAG system, retrieval pipeline diagram on laptop, technical workspace with notes.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for the Relative Date Normalization Prompt Template.

This prompt is designed for RAG developers and search engineers who need to convert relative time expressions—such as 'last quarter', 'recent', or 'next month'—into explicit, machine-readable date ranges. The core job is to anchor a user's fuzzy temporal language to a concrete reference date, producing ISO 8601 boundaries that can be directly injected into metadata filters for vector databases, keyword search indexes, or hybrid retrieval pipelines. The ideal user is someone building a production retrieval system where time-sensitive corpora (financial filings, news archives, internal documents) require precise temporal scoping to avoid irrelevant results.

Use this prompt when your retrieval pipeline accepts natural language queries that contain relative dates and you need to transform those expressions into structured filter clauses before execution. It is particularly valuable in conversational RAG systems where follow-up questions like 'what about last week?' must resolve correctly against a session-level temporal anchor. However, do not use this prompt for simple date parsing tasks where a deterministic library like dateparser or python-dateutil would suffice. The prompt is warranted when the input language is ambiguous, context-dependent, or requires reasoning about fiscal calendars, partial periods, or domain-specific recency windows that rule-based systems handle poorly.

Before implementing this prompt, ensure you have a reliable reference date source—typically the current server time in UTC or a session-level anchor from the conversation context. The prompt will fail silently or produce incorrect ranges if the reference date is missing or stale. You should also define your target timezone and decide whether output ranges should be in UTC or a local timezone. For high-stakes applications like financial compliance or legal document retrieval, always pair this prompt with a validation step that checks for logical consistency (e.g., start dates before end dates, no future-dated constraints unless explicitly requested) and log the raw model output alongside the resolved ranges for auditability. If your use case involves fiscal calendars, holiday-aware date ranges, or multi-timezone normalization, consider the sibling prompts in this content group that handle those specific scenarios rather than overloading this single template.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Relative Date Normalization Prompt works well and where it introduces risk. Use these cards to decide if this prompt fits your retrieval pipeline before you integrate it.

01

Good Fit: RAG Over Time-Sensitive Corpora

Use when: your retrieval corpus contains news, financial filings, support tickets, or logs where document age directly determines relevance. Guardrail: always pair normalized dates with a metadata filter on an indexed timestamp field; never rely on the model to rank by recency alone.

02

Bad Fit: Static Knowledge Bases

Avoid when: your corpus is a static snapshot (e.g., a textbook, a single manual version, or a fixed policy document). Guardrail: if all documents share the same effective date, skip temporal normalization entirely to avoid injecting irrelevant filter clauses that silently drop valid results.

03

Required Input: Explicit Reference Date

What to watch: relative expressions like 'last month' are meaningless without a known 'now'. Guardrail: always inject a reference timestamp (ISO 8601) into the prompt. For conversational systems, use the message timestamp, not server time, and log which anchor was used for auditability.

04

Required Input: Target Timezone

What to watch: 'today' resolves differently in UTC vs. the user's local timezone, shifting day boundaries and causing off-by-one errors. Guardrail: require an IANA timezone string (e.g., 'America/New_York') as a prompt input. Validate that the resolved range aligns with the user's expected business day.

05

Operational Risk: Silent Boundary Errors

What to watch: the model may produce a plausible-looking date range that is off by one day, one month, or one fiscal boundary without any indication of uncertainty. Guardrail: add a post-processing validator that checks range arithmetic against the reference date and flags impossible or future-dated boundaries before they hit the retrieval index.

06

Operational Risk: Over-Constraint and Empty Results

What to watch: a precisely normalized range like '2024-03-01 to 2024-03-31' may return zero documents if the corpus has sparse coverage. Guardrail: implement a fallback path that progressively relaxes the temporal constraint (e.g., expand to the enclosing quarter) and logs when relaxation was triggered for relevance tuning.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt that converts relative time expressions into explicit ISO 8601 date ranges anchored to a reference date.

This template is the core instruction set for normalizing relative date language. It accepts a user query containing temporal expressions, a reference date to anchor calculations, and optional constraints like a target timezone or fiscal calendar. The prompt instructs the model to output a structured JSON object with explicit start and end boundaries in ISO 8601 format, a confidence score, and a list of assumptions made during resolution. You can copy this template directly into your prompt management system, API call, or orchestration layer.

text
You are a precise temporal reasoning engine. Your task is to convert relative time expressions in a user query into explicit ISO 8601 date ranges.

[INPUT]
User Query: [USER_QUERY]
Reference Date: [REFERENCE_DATE] (ISO 8601 date, e.g., 2025-04-08)
Target Timezone: [TARGET_TIMEZONE] (IANA timezone, e.g., America/New_York)
Fiscal Year Start: [FISCAL_YEAR_START_MONTH_DAY] (optional, e.g., 07-01 for July 1st)

[OUTPUT_SCHEMA]
Return a valid JSON object with the following structure. Do not include any text outside the JSON object.
{
  "original_expression": "string (the extracted temporal phrase)",
  "start_date": "string (ISO 8601 date or datetime, YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS+HH:MM)",
  "end_date": "string (ISO 8601 date or datetime, exclusive end boundary)",
  "confidence": "number (0.0 to 1.0)",
  "assumptions": ["string (list of explicit assumptions made during resolution)"],
  "alternative_ranges": [
    {
      "start_date": "string",
      "end_date": "string",
      "rationale": "string (why this alternative exists)"
    }
  ]
}

[CONSTRAINTS]
1. Always use the provided Reference Date as the anchor for relative calculations.
2. If the Target Timezone is provided, all datetime boundaries must be in that timezone and include the UTC offset.
3. For fiscal quarter references (e.g., 'Q3'), use the Fiscal Year Start if provided; otherwise, assume a calendar year and note this in assumptions.
4. For vague terms like 'recent' or 'latest', provide a primary range and at least one alternative range with a rationale.
5. If the temporal expression is ambiguous or cannot be resolved with high confidence (confidence < 0.7), still provide the best estimate but flag the ambiguity in assumptions.
6. If no temporal expression is found, return null for start_date and end_date and set confidence to 0.0.
7. Handle month-end rollover correctly (e.g., 'last month' on March 31st should resolve to the full month of February).
8. For 'next [day of week]', calculate the correct upcoming occurrence from the Reference Date.

[EXAMPLES]
Example 1:
User Query: "Show me sales from last quarter"
Reference Date: 2025-04-08
Target Timezone: America/Chicago
Fiscal Year Start: null
Output:
{
  "original_expression": "last quarter",
  "start_date": "2025-01-01T00:00:00-06:00",
  "end_date": "2025-04-01T00:00:00-05:00",
  "confidence": 0.95,
  "assumptions": ["Calendar year quarters assumed since no fiscal year start provided."],
  "alternative_ranges": []
}

Example 2:
User Query: "What were the recent support tickets about?"
Reference Date: 2025-04-08
Target Timezone: UTC
Fiscal Year Start: null
Output:
{
  "original_expression": "recent",
  "start_date": "2025-03-25T00:00:00Z",
  "end_date": "2025-04-08T00:00:00Z",
  "confidence": 0.6,
  "assumptions": ["'Recent' interpreted as a 14-day window, a common default for support contexts."],
  "alternative_ranges": [
    {
      "start_date": "2025-04-01T00:00:00Z",
      "end_date": "2025-04-08T00:00:00Z",
      "rationale": "Alternative interpretation: 'recent' could mean the last 7 days."
    },
    {
      "start_date": "2025-03-08T00:00:00Z",
      "end_date": "2025-04-08T00:00:00Z",
      "rationale": "Alternative interpretation: 'recent' could mean the last 30 days."
    }
  ]
}

To adapt this template, replace the square-bracket placeholders with your application's runtime values. The [USER_QUERY] and [REFERENCE_DATE] are mandatory; [TARGET_TIMEZONE] and [FISCAL_YEAR_START_MONTH_DAY] are optional but critical for accuracy in global or financial applications. If your retrieval system expects Unix timestamps or a different date format, modify the [OUTPUT_SCHEMA] description accordingly. The [EXAMPLES] section is crucial for few-shot behavior—add at least two more examples that reflect your domain's common temporal expressions and edge cases. For production, consider moving the output schema into your application's JSON mode or function-calling tool definition to guarantee structural validity, and use the prompt's confidence field to trigger a clarification workflow when it falls below a threshold like 0.7.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the Relative Date Normalization Prompt Template. Each placeholder must be populated before the prompt is assembled and sent to the model. Validation notes describe how to check the input before execution.

PlaceholderPurposeExampleValidation Notes

[RELATIVE_TIME_EXPRESSION]

The natural language time expression to normalize into explicit date boundaries.

last quarter

Must be a non-empty string. Reject null or whitespace-only input. Length should not exceed 200 characters to avoid compound-expression ambiguity.

[REFERENCE_DATE]

The anchor date from which relative expressions are resolved. Typically the current date or the date of the query.

2025-01-15

Must be a valid ISO 8601 date string (YYYY-MM-DD). Reject future dates if the use case requires historical-only resolution. Validate month and day ranges.

[TIMEZONE]

The IANA timezone identifier used to resolve day boundaries and date arithmetic.

America/New_York

Must be a valid IANA timezone string from the tz database. Reject unrecognized values. Default to UTC if not provided, but log the default for audit.

[OUTPUT_SCHEMA]

The expected JSON schema for the normalized date range output, including field names and types.

{"start_date": "string", "end_date": "string", "inclusive": "boolean"}

Must be a valid JSON Schema object or a concise type description. Validate parseability before injection. Reject schemas that omit required boundary fields.

[FISCAL_CALENDAR]

Optional fiscal calendar definition for resolving fiscal quarters and years. Null if not applicable.

{"fiscal_year_start": "07-01", "fiscal_year_end": "06-30"}

If provided, must contain valid month-day pairs for fiscal year boundaries. Validate month values 01-12 and day values 01-31. Allow null when fiscal resolution is not required.

[HOLIDAY_CALENDAR]

Optional locale-specific holiday calendar for resolving holiday-based expressions. Null if not applicable.

{"locale": "US", "year": 2025}

If provided, must include a valid locale code and year. Validate locale against a known list. Allow null. When null, holiday expressions should trigger a clarification request or fallback.

[AMBIGUITY_PREFERENCE]

Instruction for how to handle ambiguous expressions: prefer narrowest range, widest range, or return multiple candidates.

narrowest

Must be one of: narrowest, widest, multiple_candidates. Reject unrecognized values. Default to narrowest if not provided, but log the default.

[MAX_RANGE_DAYS]

Optional upper bound on the resolved date range in days. Prevents unbounded ranges from expressions like 'all time'.

365

If provided, must be a positive integer. Validate that resolved ranges do not exceed this value. Allow null when no upper bound is desired, but log unbounded resolutions for review.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Relative Date Normalization prompt into a production retrieval pipeline with validation, retries, and observability.

This prompt is designed to sit immediately before your retrieval step in a RAG pipeline. It takes a raw user query and a reference timestamp, normalizes all relative time expressions into explicit ISO 8601 date ranges, and returns structured boundaries that your application can convert directly into metadata filter clauses for vector databases, search indexes, or SQL WHERE statements. The prompt is stateless by design—every call must receive a fresh reference date, which makes it safe to deploy behind a stateless API endpoint or as a pre-processing step in a queue-based retrieval worker.

The implementation should enforce a strict contract around the reference date. Always inject the current server timestamp as [REFERENCE_TIMESTAMP] in ISO 8601 format with an explicit UTC offset (e.g., 2025-03-15T14:30:00+00:00). If your application supports user-level timezone preferences, resolve the reference date to the user's local timezone before passing it to the prompt. For session-based conversational RAG, store the conversation start time as the anchor and reuse it across all turns in that session to prevent temporal drift. Validate the model's output against a JSON schema that requires start_date and end_date fields in ISO 8601 format, an expression_type enum (e.g., relative_range, absolute_range, open_ended), and a confidence float between 0.0 and 1.0. Reject any response that fails schema validation and retry once with a stronger constraint instruction before falling back to a default 30-day window.

Log every normalization result alongside the original query, the reference timestamp, and the model version for debugging and eval. Common failure modes include the model defaulting to calendar-year boundaries when the user meant a fiscal year, misinterpreting 'last' as 'previous completed period' vs. 'trailing N days', and mishandling month-end rollover for dates like January 31st when adding a month. Build a small eval harness with 20-30 edge cases covering these scenarios, and run it against every prompt or model change before deployment. For high-stakes financial or legal retrieval, route low-confidence outputs (confidence < 0.85) to a human review queue or a secondary clarification prompt before executing the retrieval. This prompt is a pre-retrieval transform, not a retrieval strategy—pair it with your existing hybrid search or vector database query builder to convert the normalized boundaries into the filter syntax your backend expects.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, types, and validation rules for the normalized date range output. Use this contract to parse the model response and validate correctness before passing boundaries to a retrieval system.

Field or ElementType or FormatRequiredValidation Rule

reference_date

ISO 8601 date string (YYYY-MM-DD)

Must parse as a valid date. Must match the [REFERENCE_DATE] input if provided; otherwise, must be the current date at generation time.

original_expression

string

Must be a non-empty substring of [USER_QUERY]. If no temporal expression is found, must be null.

start_date

ISO 8601 date string (YYYY-MM-DD)

Must parse as a valid date. Must be on or before end_date. For open-ended ranges like 'since 2020', set to the earliest boundary implied.

end_date

ISO 8601 date string (YYYY-MM-DD)

Must parse as a valid date. Must be on or after start_date. For open-ended ranges like 'until last month', set to the latest boundary implied.

inclusive_start

boolean

Must be true if the range includes the start_date boundary, false otherwise. Default to true unless the expression explicitly excludes the boundary.

inclusive_end

boolean

Must be true if the range includes the end_date boundary, false otherwise. Default to true unless the expression explicitly excludes the boundary.

confidence

number (0.0 to 1.0)

Must be a float between 0.0 and 1.0. Values below 0.7 should trigger a clarification request or human review. Ambiguous expressions like 'recent' must score lower than explicit ranges.

assumptions

array of strings

If confidence is below 0.9, this field must be present and list the assumptions made to resolve the range. Each string must describe one assumption. Empty array allowed when confidence is high.

PRACTICAL GUARDRAILS

Common Failure Modes

Relative date normalization fails silently and often. These are the most common production failure patterns and the specific checks that catch them before they corrupt retrieval results.

01

Missing or Stale Reference Date

What to watch: The prompt resolves 'last quarter' or 'next month' without an explicit reference date, defaulting to the model's training cutoff or the current UTC time. This produces wrong boundaries when the system clock drifts, the request is replayed, or the user's local date differs from server time. Guardrail: Always inject a [REFERENCE_DATE] variable with an explicit ISO 8601 date. Validate that every resolved range falls within a reasonable window around that anchor before retrieval executes.

02

Month-End Boundary Rollover Errors

What to watch: Prompts that generate date ranges for 'last month' or 'end of quarter' mishandle months with 28, 29, 30, or 31 days. A naive 'subtract one month' operation on March 31 produces March 3 instead of February 28, shifting the entire retrieval window. Guardrail: Add a post-processing validator that checks every generated boundary for calendar validity. Reject any end-of-month date that does not match the actual last day of the target month given the reference year.

03

Timezone-Silent UTC Assumption

What to watch: The prompt normalizes 'today' or 'yesterday' to UTC midnight without considering the user's or document corpus timezone. A query at 11 PM PST on Monday for 'today's reports' retrieves documents timestamped Tuesday UTC, missing the intended day entirely. Guardrail: Require a [TIMEZONE] input variable. Normalize all generated boundaries to UTC with explicit offset notation. Add an eval check that verifies the resolved range covers the correct local calendar day before retrieval.

04

Ambiguous Recency Without Domain Window

What to watch: Queries containing 'recent', 'latest', or 'current' are resolved to arbitrary windows (7 days, 30 days) without considering the domain. A 'recent earnings report' should look back one quarter, while 'recent security alerts' should look back hours. A single default produces irrelevant results. Guardrail: Map recency terms to domain-specific windows using a [DOMAIN_RECENCY_MAP] configuration. When the domain is unknown, generate multiple candidate ranges with confidence scores and let the retrieval layer rank or merge results.

05

Fiscal vs. Calendar Year Confusion

What to watch: The prompt treats 'Q3' or 'YTD' as calendar periods when the target corpus uses a fiscal calendar with a different year start. A 'Q3 2024' query against a fiscal-year-starting-in-February corpus retrieves the wrong three-month window. Guardrail: Inject a [FISCAL_CALENDAR] definition when the corpus uses non-calendar fiscal periods. Validate that resolved quarter boundaries align with the declared fiscal month offsets. Flag any quarter resolution that assumes January year-start without explicit confirmation.

06

Open-Ended Range Without Upper Bound

What to watch: Queries like 'since January' or 'from 2020 onward' generate ranges with a start date but no end date, causing retrieval to scan the entire index forward. This produces timeouts, excessive result sets, or stale documents ranked above recent ones. Guardrail: Always cap open-ended ranges with an explicit [MAX_RANGE_END] default (typically the reference date or current timestamp). Log a warning when an unbounded range is generated so operators can review the retrieval scope.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the relative date normalization prompt before shipping. Each criterion targets a known failure mode in temporal expression resolution.

CriterionPass StandardFailure SignalTest Method

ISO 8601 Boundary Accuracy

Start and end dates match ground truth for the given [REFERENCE_DATE] and [TIMEZONE]

Off-by-one-day errors, wrong month, or year rollover mistakes

Run 20 test cases with known relative expressions and compare output to manually calculated ISO 8601 ranges

Timezone Consistency

All output timestamps include the correct UTC offset for [TIMEZONE] and handle DST transitions appropriately

Missing timezone offset, UTC conversion errors, or DST boundary off-by-one-hour

Test with timezones that have DST transitions (e.g., America/New_York, Europe/London) and verify offset correctness at boundary dates

Month-End Rollover Handling

Expressions like 'last month' on March 31 correctly resolve to February 1-28/29 range

February 31 or other impossible dates, incorrect month length assumptions

Test on months ending in 28, 29, 30, and 31 days with relative expressions that cross month boundaries

Ambiguous Expression Flagging

Prompt returns a confidence score below threshold or a clarification request for expressions like 'recent' or 'soon'

High-confidence output for inherently vague terms without domain context

Feed 10 vague temporal expressions and verify the prompt either abstains, flags low confidence, or proposes multiple candidate ranges with explicit assumptions

Multi-Part Range Resolution

Queries with multiple temporal constraints (e.g., 'last week of Q2') produce a single correct range

Overlapping or contradictory ranges, missing intersection logic

Test compound expressions against manually computed ranges and verify the output is the intersection of all constraints

Leap Year Handling

February 29 is included in ranges that span leap years, and year-length calculations account for 366 days

February 29 missing from ranges, incorrect day counts for year-based intervals

Test with [REFERENCE_DATE] in leap years and non-leap years, verifying February ranges and 'last 365 days' calculations

Future Date Constraint Validation

Expressions like 'next month' produce ranges that start after [REFERENCE_DATE] and are logically consistent

Past dates returned for future-oriented expressions, or ranges that include the reference date when they should not

Test future-oriented expressions and verify all boundary dates are strictly after [REFERENCE_DATE]

Output Schema Compliance

Every output includes all required fields: start_date, end_date, expression_type, confidence, assumptions_made

Missing fields, extra fields, wrong types, or null values in required fields

Validate output against a JSON Schema definition for every test case; reject any output that fails schema validation

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a hardcoded reference date and minimal output validation. Accept the model's raw date range output and log it for manual spot-checking.

code
Reference date: [TODAY_ISO]
Query: [USER_QUERY]

Return a JSON object with "start_date" and "end_date" in ISO 8601 format.

Watch for

  • Missing timezone assumptions causing off-by-one-day errors
  • Model inventing dates when the query has no temporal expression
  • Month-end rollover producing invalid dates (e.g., March 31 + 1 month)
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.