Skip to content
Sarj Code Standards

prefer-semantic-temporal-types

Use semantic types for temporal fields and function boundaries.

Why

Primitive numbers erase the distinction between instants and durations and allow accidental mixing of units. Strings leave Pydantic instant fields unparsed.

Fix

Represent instants with datetime, or Pydantic AwareDatetime when timezone awareness is required. Represent durations and TTLs with timedelta. Convert explicit units at boundaries and preserve the serialized contract.

Examples

Before — flagged An epoch instant erases its temporal type
app/models.py
from pydantic import BaseModel
class CacheEntry(BaseModel):
created_ms: int
ttl_seconds: float = 60
After — preferred Instants and durations retain distinct types
app/models.py
from datetime import timedelta
from pydantic import BaseModel, AwareDatetime
class CacheEntry(BaseModel):
created_at: AwareDatetime
ttl: timedelta
Before — flagged A native settings model retains an epoch integer
app/settings.py
import pydantic_settings as ps
class Settings(ps.BaseSettings):
created_ms: int
After — preferred The native settings model declares an aware instant
app/settings.py
import pydantic_settings as ps
from pydantic import AwareDatetime
class Settings(ps.BaseSettings):
created_at: AwareDatetime
Before — flagged A model instant and a function timeout use primitives
app/models.py
from pydantic import BaseModel
class CacheEntry(BaseModel):
queued_at: str
def flush(timeout_seconds: float | None) -> None:
pass
After — preferred A model instant and a function timeout retain their types
app/models.py
from datetime import timedelta
from pydantic import AwareDatetime, BaseModel
class CacheEntry(BaseModel):
queued_at: AwareDatetime
def flush(timeout: timedelta | None) -> None:
pass