Install & Compatibility
Where this runs
tested against v0.14.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.920 runs
installs and imports cleanly · install 0.0s · import 0.748s · 42.6MB
glibcpy 3.10–3.920 runs
installs and imports cleanly · install 3.5s · import 0.701s · 41MB
45MB installed
● package 45MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
UtcDateTime
✓ from sqlalchemy_utc import UtcDateTime
utcnow
✓ from sqlalchemy_utc import utcnow
✗ from datetime import datetime; datetime.utcnow()
The standard `datetime.utcnow()` is deprecated in Python 3.13+ and does not return timezone-aware objects. `sqlalchemy_utc.utcnow` provides a dialect-aware UTC function.
This quickstart demonstrates defining a SQLAlchemy model with `UtcDateTime` columns, using `utcnow()` for default and on-update values. It then creates, retrieves, and updates an event, verifying that the `datetime` objects returned are always timezone-aware and in UTC.
import datetime
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker, declarative_base
from sqlalchemy_utc import UtcDateTime, utcnow
# Setup database (using SQLite for simplicity)
engine = create_engine('sqlite:///./test.db')
Base = declarative_base()
class Event(Base):
__tablename__ = 'events'
id = Column(Integer, primary_key=True)
name = Column(String)
created_at = Column(UtcDateTime, default=utcnow)
updated_at = Column(UtcDateTime, default=utcnow, onupdate=utcnow)
def __repr__(self):
return f"<Event(id={self.id}, name='{self.name}', created_at={self.created_at}, updated_at={self.updated_at})>"
# Create tables
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
# Create a new event
new_event = Event(name='Meeting Start')
session.add(new_event)
session.commit()
print(f"Created event: {new_event}")
# Retrieve and verify timezone
retrieved_event = session.query(Event).filter_by(name='Meeting Start').first()
print(f"Retrieved event: {retrieved_event}")
assert retrieved_event.created_at.tzinfo == datetime.timezone.utc
print("Created_at is UTC aware.")
# Update an event
retrieved_event.name = 'Meeting Concluded'
session.add(retrieved_event)
session.commit()
print(f"Updated event: {retrieved_event}")
assert retrieved_event.updated_at.tzinfo == datetime.timezone.utc
print("Updated_at is UTC aware.")
session.close()
Errors
Common errors & fixes
AttributeError: 'datetime.datetime' object has no attribute 'tzinfo'
Attempting to assign a naive `datetime` object to a `UtcDateTime` column or performing an operation that assumes `tzinfo` on a naive object returned from a non-UtcDateTime column.
fixEnsure all `datetime` objects interacting with `UtcDateTime` columns are timezone-aware, e.g., `datetime.datetime.now(datetime.timezone.utc)`.
SQLAlchemy's DateTime(timezone=True) loses timezone information when fetching from SQLite/MySQL.
The underlying database (SQLite/MySQL) does not natively support `TIMESTAMP WITH TIME ZONE`, causing SQLAlchemy's default `DateTime(timezone=True)` to often store/retrieve naive datetimes or local times without proper conversion.
fixReplace `DateTime(timezone=True)` with `UtcDateTime` from `sqlalchemy-utc`. This library explicitly handles the conversions to ensure UTC storage and timezone-aware retrieval on these databases.
Timestamps retrieved from PostgreSQL are in local time instead of UTC, even if stored as UTC.
PostgreSQL connections have an associated timezone, which defaults to the system's timezone. If not explicitly set to UTC, `TIMESTAMP WITHOUT TIME ZONE` values (which is how `UtcDateTime` might map on some systems) will be interpreted as local time on retrieval, or `TIMESTAMP WITH TIME ZONE` might be converted.
fixConfigure the SQLAlchemy engine to ensure connections use UTC, e.g., `create_engine('postgresql://user:pass@host/db', connect_args={'options': '-c timezone=utc'})` or verify that PostgreSQL's `TimeZone` setting is 'UTC'. Upgrade
Version history
0.14.0latest on PyPI · released Sep 24, 2021
Audit
Dependencies
SQLAlchemyrequiredCore ORM library that sqlalchemy-utc extends.