Skip to content
Discussion options

You must be logged in to vote

You can implement this using PlainValidator:

from datetime import datetime
from typing import Annotated, TypeAlias
from fastapi import FastAPI, Query
from pydantic import PlainValidator

app = FastAPI()

def validate_date_time(value: str):
    try:
        return datetime.strptime(value, "%Y-%m-%dT%H:%M%z")
    except ValueError as error:
        raise ValueError("Invalid datetime") from error

MyDateTime: TypeAlias = Annotated[datetime, PlainValidator(validate_date_time)]

@app.get("/test")
def test_route(time_1: Annotated[MyDateTime, Query(description="ISO8601 timestamp")]):
    print(time_1)  # This is always a datetime
    return time_1

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@ahmedrafayat
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by YuriiMotov
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question or problem
3 participants