How to record created and updated times¶
This page gives a model created_at and updated_at fields: a field default sets both when the row is created, and a mixin sets updated_at again in every save().
The TimestampMixin¶
Declare both fields on the model with a default of the current UTC time, and put the mixin first among the bases so its save() runs before Model.save():
from datetime import UTC, datetime
from ferro import Field, Model, connect, engines
def utcnow() -> datetime:
return datetime.now(UTC)
class TimestampMixin:
"""Set ``updated_at`` on every save.
A plain class, not a ``Model`` subclass: each model that uses it
declares ``created_at`` and ``updated_at`` itself.
"""
async def save(self, **kwargs) -> None:
self.updated_at = utcnow()
await super().save(**kwargs)
class Note(TimestampMixin, Model):
id: int | None = Field(default=None, primary_key=True)
text: str
created_at: datetime = Field(default_factory=utcnow)
updated_at: datetime = Field(default_factory=utcnow)
await connect("sqlite::memory:", auto_migrate=True)
async with engines.session():
note = await Note.create(text="First draft")
assert note.created_at.tzinfo is UTC
from datetime import UTC, datetime
from typing import Annotated
from ferro import Field, Model, connect, engines
def utcnow() -> datetime:
return datetime.now(UTC)
class TimestampMixin:
"""Set ``updated_at`` on every save.
A plain class, not a ``Model`` subclass: each model that uses it
declares ``created_at`` and ``updated_at`` itself.
"""
async def save(self, **kwargs) -> None:
self.updated_at = utcnow()
await super().save(**kwargs)
class Note(TimestampMixin, Model):
id: Annotated[int | None, Field(primary_key=True)] = None
text: str
created_at: datetime = Field(default_factory=utcnow)
updated_at: datetime = Field(default_factory=utcnow)
await connect("sqlite::memory:", auto_migrate=True)
async with engines.session():
note = await Note.create(text="First draft")
assert note.created_at.tzinfo is UTC
The new note's created_at is an aware datetime in UTC. create() saves through save(), so the mixin runs for it too. The blocks below run inside this session; Sessions explains why every call needs one.
The mixin is a plain class, not a Model subclass, so every model that uses it declares the two fields itself. A Model base class would get a table of its own; Fields on a model base class shows that table.
Updating a note¶
Change a field and save, and the mixin moves updated_at forward:
created = note.created_at
edited_before = note.updated_at
note.text = "Second draft"
await note.save()
assert note.created_at == created
assert note.updated_at > edited_before
created_at keeps the time the note was created, and updated_at is now later than before the save.
Batch updates¶
Batch updates skip the mixin
Note.where(...).update(...) writes its columns in one UPDATE statement without loading the rows, so no save() runs and updated_at keeps its old value unless the update sets it.
Pass updated_at=utcnow() beside the columns the update changes:
archived = await Note.create(text="Old idea")
await Note.create(text="Shopping list")
touched = await Note.where(lambda note: note.text == "Old idea").update(
text="Old idea (archived)", updated_at=utcnow()
)
assert touched == 1
latest = (
await Note.select().order_by(lambda note: note.updated_at, "desc").first()
)
assert latest.text == "Old idea (archived)"
assert latest.updated_at.tzinfo is not None
The archived note now has the latest updated_at, so it sorts first, and it reads back as an aware datetime that compares with utcnow(). Ferro stores utcnow() in an update exactly as save() stores it, so rows touched either way sort together.
now on SQLite
The database-clock recipe update(lambda note: {"updated_at": now}) writes SQLite's own time format, whole seconds with no time zone (2026-10-19 14:56:27), while save() writes 2026-10-19T14:56:27.736246Z. SQLite compares the two as text, so such a row sorts before every row save() wrote on the same day, however much earlier. It also reads back as a naive datetime, which raises TypeError when compared with utcnow(). Use utcnow() on SQLite; on Postgres, now stores a timestamptz like any other.
Storing UTC¶
utcnow() returns datetime.now(UTC), an aware datetime. A naive datetime.now() reads the server's local clock, so its values change meaning between hosts and across daylight-saving changes. Store UTC and convert to the reader's time zone when you display the value.
Naive and aware columns¶
A datetime field is a timestamptz column on Postgres; SQLite stores both kinds as text. If a model's datetime field points at an existing timestamp column (no time zone), auto-migrate warns and leaves the column as it is: casting timestamp to timestamptz reads the stored values in the connection's time zone and can shift them.
- To keep the column naive, declare the field with
db_type="timestamp". - To convert it, write the cast yourself with an explicit source time zone, such as
USING occurred_at AT TIME ZONE 'UTC', in a hand-written migration step or an Alembic revision.
See also¶
- Fields on a model base class: why the fields go on each model.
- How to soft-delete rows: the same mixin pattern for deletion.
- Batch updates and deletes and
Query.update()in the API reference.