CodexBloom - Programming Q&A Platform

FastAPI Automatically Converts Timestamp to UTC, Causing Confusion with Local Timezones

πŸ‘€ Views: 48 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-24
fastapi datetime pydantic sqlalchemy Python

I'm stuck on something that should probably be simple. I'm working on a FastAPI application where I'm trying to handle timestamps that are user-supplied in local time. However, when I define a Pydantic model like this: ```python from pydantic import BaseModel from datetime import datetime class Event(BaseModel): event_time: datetime ``` and send a request with a timestamp in local time, FastAPI seems to automatically convert it to UTC. For example, if I send `2023-10-05T15:00:00` (assuming it's in Eastern Daylight Time), the logged output shows it as `2023-10-05T19:00:00Z`, which is UTC. I've tried adding a custom validator to convert the incoming time to the desired timezone using `pytz`, but I still end up with the same UTC representation in my database: ```python import pytz from fastapi import FastAPI, HTTPException from datetime import datetime app = FastAPI() @app.post("/events/") async def create_event(event: Event): local_tz = pytz.timezone('America/New_York') local_time = event.event_time.astimezone(local_tz) print(local_time) # This shows the correct local time but I need to save it correctly # Saving to database logic here ``` The logged output prints the local time correctly, but by the time I save it in the database, it’s back to UTC, which is not what I want. I’ve also checked my SQLAlchemy configuration, and it should handle naive datetime objects as local time. Am I missing something in how FastAPI handles datetime conversions, or is there a better way to manage timezones with this framework? Any insights would be greatly appreciated! Any ideas what could be causing this?