Skip to content

Comments

fix: replace deprecated datetime.utcnow() with timezone-aware equivalent#241

Open
Aiudadadadf wants to merge 1 commit intoklen:masterfrom
Aiudadadadf:fix/utcnow-deprecation
Open

fix: replace deprecated datetime.utcnow() with timezone-aware equivalent#241
Aiudadadadf wants to merge 1 commit intoklen:masterfrom
Aiudadadadf:fix/utcnow-deprecation

Conversation

@Aiudadadadf
Copy link

MigrateHistory.migrated_at uses dt.datetime.utcnow as its default callable. datetime.datetime.utcnow() was deprecated in Python 3.12 and emits a DeprecationWarning on every call. Projects that run their test suite with filterwarnings = error - a common hardening step - see test failures whenever any migration is applied, even in otherwise unrelated tests.

The root cause is in peewee_migrate/models.py, line 14:

migrated_at = pw.DateTimeField(default=dt.datetime.utcnow)

The replacement is lambda: dt.datetime.now(dt.timezone.utc).replace(tzinfo=None). This produces a naive UTC datetime identical in value to what utcnow() returned, so existing rows and comparisons are unaffected. The tzinfo is stripped before storing so peewee's DateTimeField behaviour (which expects naive datetimes by default) is preserved.

Reproduction steps on Python 3.12+:

import warnings
import datetime as dt

warnings.filterwarnings("error", category=DeprecationWarning)
dt.datetime.utcnow()  # raises DeprecationWarning

The warning text is:

DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal
in a future version. Use timezone-aware objects to represent datetimes in UTC:
datetime.datetime.now(datetime.UTC).

Verified the fix produces an equivalent naive UTC datetime:

>>> import datetime as dt
>>> dt.datetime.now(dt.timezone.utc).replace(tzinfo=None)
datetime.datetime(2026, 2, 23, 19, 58, 42, 123456)

Fixes #240

@Aiudadadadf Aiudadadadf requested a review from klen as a code owner February 23, 2026 20:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant