Skip to content

Instantly share code, notes, and snippets.

@nimaxin
nimaxin / sqlalchemy_asyncpg_timezone_datetime.py
Created April 26, 2025 10:23
SQLAlchemy's custom type to store timezone aware datetimes in PostgreSQL (via asyncpg) and automatically convert to local timezones (e.g., Europe/Berlin) when querying. Solves timezone handling for databases with clean ORM integration.
import asyncio
from datetime import datetime, timezone
import pytz
import sqlalchemy as sa
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy.types import TypeDecorator