DateTime Output Parser

Key Notes

  • DateTimeOutputParser is no longer part of LangChain.

  • Use Pydantic models with datetime fields instead.

  • The LLM should output JSON with ISO date format (YYYY-MM-DD) to make parsing reliable.

  • This method works for any structured data containing dates, times, or timestamps.

What it is A DateTime Output Parser converts LLM text output that represents a date or time into a Python datetime object. This ensures the AI’s response can be used directly in code without manual string parsing.

Why it exists LLMs often return dates in inconsistent formats (e.g., "Jan 8, 2026", "08/01/2026", "2026-01-08"). A parser standardizes this output so your program can handle it reliably.

Real-world analogy It’s like taking various clocks or calendars and converting all their readings into a single standard format, so you can schedule meetings accurately.

Minimal beginner example

import os
from dotenv import load_dotenv
from datetime import datetime
from pydantic import BaseModel, validator
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.output_parsers import PydanticOutputParser
from langchain_core.prompts import PromptTemplate

load_dotenv()
api_key = os.getenv("GEMINI_API_KEY")

llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", api_key=api_key)

# Step 1: Define a Pydantic model with a datetime field
class PersonDOB(BaseModel):
    name: str
    dob: datetime

    # Optional: Convert string to datetime if needed
    @validator("dob", pre=True)
    def parse_date(cls, v):
        return datetime.fromisoformat(v.strip())

# Step 2: Create a Pydantic parser
parser = PydanticOutputParser(pydantic_object=PersonDOB)

# Step 3: Prompt the LLM to return JSON
prompt = PromptTemplate(
    template="""
Provide Elon Musk's name and date of birth in JSON format:
{{"name": "Elon Musk", "dob": "YYYY-MM-DD"}}
""",
    input_variables=[]
)

# Step 4: Run LLM and parse output
response = llm.invoke(prompt.format())
parsed_output = parser.parse(response.content)

print(parsed_output)
print(parsed_output.name, parsed_output.dob)  # dob is a datetime object

Small LangChain workflow

  1. Prepare a prompt asking for a date or datetime.

  2. Send it to the LLM.

  3. Parse output with DateTimeOutputParser.

  4. Use the datetime object in chains, calculations, or scheduling.

Common beginner mistakes

  • LLM returns a format not matching the parser’s date_format.

  • Forgetting to specify date_format, leading to parsing errors.

  • Using this parser for text that isn’t a date → parser fails.

When to use this vs alternatives

  • Use DateTimeOutputParser for date or time outputs.

  • Use PydanticOutputParser if the date is part of a larger structured object.

  • Use JSONOutputParser if dates are returned in a JSON object but may need further conversion.

Last updated