Skip to content

The agent that grows with you

ci: ruff UP017 fixes

Maciej Lisiewski9eab688b429b
diff --git a/acp_adapter/server.py b/acp_adapter/server.py
index 6032714a994..6421b21525b 100644
--- a/acp_adapter/server.py
+++ b/acp_adapter/server.py
@@ -3,7 +3,7 @@
from __future__ import annotations
import asyncio
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
import contextlib
import contextvars
import logging
@@ -415,7 +415,7 @@ class HermesACPAgent(SlashCommandsMixin, acp.Agent):
update = SessionInfoUpdate(
session_update="session_info_update",
title=title if isinstance(title, str) and title.strip() else None,
- updated_at=datetime.now(timezone.utc).isoformat(),
+ updated_at=datetime.now(UTC).isoformat(),
field_meta=self._provenance_meta(
session_id, current_hermes_session_id or session_id, previous_hermes_session_id
),
diff --git a/acp_adapter/session.py b/acp_adapter/session.py
index aac34a5e4b6..1f6b2813bd5 100644
--- a/acp_adapter/session.py
+++ b/acp_adapter/session.py
@@ -17,7 +17,7 @@ import sys
import threading
import time
import uuid
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
@@ -63,7 +63,7 @@ def _format_updated_at(value: Any) -> str | None:
if value is None or (isinstance(value, str) and value.strip()):
return value
try:
- return datetime.fromtimestamp(float(value), tz=timezone.utc).isoformat()
+ return datetime.fromtimestamp(float(value), tz=UTC).isoformat()
except Exception:
return None
diff --git a/agent/account_usage.py b/agent/account_usage.py
index f1ae4fa74c5..6a18127e5d2 100644
--- a/agent/account_usage.py
+++ b/agent/account_usage.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import logging
import math
from dataclasses import dataclass
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import TYPE_CHECKING, Any, Callable, Optional
import httpx
@@ -23,7 +23,7 @@ _DEPLETED_LINE = "Status: access depleted — top up to restore"
def _utc_now() -> datetime:
- return datetime.now(timezone.utc)
+ return datetime.now(UTC)
@dataclass(frozen=True)
@@ -74,13 +74,13 @@ def _parse_dt(value: Any) -> Optional[datetime]:
if value in {None, ""}:
return None
if isinstance(value, (int, float)):
- return datetime.fromtimestamp(float(value), tz=timezone.utc)
+ return datetime.fromtimestamp(float(value), tz=UTC)
if not isinstance(value, str) or not (text := value.strip()):
return None
text = text[:-1] + "+00:00" if text.endswith("Z") else text
try:
dt = datetime.fromisoformat(text)
- return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
+ return dt if dt.tzinfo else dt.replace(tzinfo=UTC)
except ValueError:
return None
diff --git a/agent/credential_pool.py b/agent/credential_pool.py
index ad726e3dbf3..e1e7d734340 100644
--- a/agent/credential_pool.py
+++ b/agent/credential_pool.py
@@ -13,7 +13,7 @@ import time
import uuid
import re
from dataclasses import dataclass, fields, replace
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple
@@ -1912,7 +1912,7 @@ class CredentialPool(CredentialPoolAdminMixin, CredentialPoolModelCooldownMixin)
"message": str(exc),
"reason": "credential_pool_refresh_failure",
"relogin_required": True,
- "at": datetime.now(timezone.utc).isoformat(),
+ "at": datetime.now(UTC).isoformat(),
}
_save_provider_state(auth_store, self.provider, state)
_save_auth_store(auth_store)
diff --git a/agent/curator.py b/agent/curator.py
index c05c148cd4a..a890fd3fb69 100644
--- a/agent/curator.py
+++ b/agent/curator.py
@@ -17,7 +17,7 @@ import threading
import time
from collections import Counter
from contextvars import copy_context
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
from typing import Any, Callable, Dict, List, NamedTuple, Optional, Set
@@ -165,7 +165,7 @@ def should_run_now(now: Optional[datetime] = None) -> bool:
return False
state = load_state()
last = _parse_iso(state.get("last_run_at"))
- now = now or datetime.now(timezone.utc)
+ now = now or datetime.now(UTC)
if last is None:
try:
state["last_run_at"] = now.isoformat()
@@ -175,7 +175,7 @@ def should_run_now(now: Optional[datetime] = None) -> bool:
logger.debug("Failed to seed curator last_run_at: %s", e)
return False
if last.tzinfo is None:
- last = last.replace(tzinfo=timezone.utc)
+ last = last.replace(tzinfo=UTC)
return (now - last) >= timedelta(hours=get_interval_hours())
@@ -212,7 +212,7 @@ def apply_automatic_transitions(now: Optional[datetime] = None) -> dict[str, int
Returns a counter dict."""
from tools import skill_usage as _u
- now = now or datetime.now(timezone.utc)
+ now = now or datetime.now(UTC)
stale_cutoff = now - timedelta(days=get_stale_after_days())
archive_cutoff = now - timedelta(days=get_archive_after_days())
# Cron-referenced skills are in use by definition (usage only bumps when a
@@ -243,7 +243,7 @@ def apply_automatic_transitions(now: Optional[datetime] = None) -> dict[str, int
# Never-active skills anchor on created_at so they don't self-archive.
anchor = _parse_iso(row.get("last_activity_at")) or _parse_iso(row.get("created_at")) or now
if anchor.tzinfo is None:
- anchor = anchor.replace(tzinfo=timezone.utc)
+ anchor = anchor.replace(tzinfo=UTC)
current = row.get("state", _u.STATE_ACTIVE)
# use_count == 0 is absence of evidence, not staleness: never archive a
# never-used skill younger than stale_after_days.
@@ -923,7 +923,7 @@ def run_curator_review(
*dry_run* SKIPS the stale/archive transitions and instructs the fork to report only; REPORT.md is still written and
recorded in ``state.last_report_path`` so users can read what WOULD have happened."""
consolidate = get_consolidate() if consolidate is None else consolidate
- start = datetime.now(timezone.utc)
+ start = datetime.now(UTC)
hermes_home = get_hermes_home() # the LLM pass may run on a thread with no profile binding
if dry_run: # count candidates without mutating state
counts = {"checked": len(_safe_curated_report()), "marked_stale": 0, "archived": 0, "reactivated": 0}
@@ -967,7 +967,7 @@ def run_curator_review(
# Prune-only run: record it and write a report, but never fork.
final_summary = f"{prefix}{auto_summary}; llm: skipped (consolidation off)"
llm_meta = _llm_meta("skipped (consolidation off)")
- elapsed = (datetime.now(timezone.utc) - start).total_seconds()
+ elapsed = (datetime.now(UTC) - start).total_seconds()
state2 = {**load_state(), "last_run_duration_seconds": elapsed, "last_run_summary": final_summary}
# Per-run report, best-effort; path recorded for `hermes curator status`.
after_report = _safe_curated_report()
diff --git a/agent/curator_backup.py b/agent/curator_backup.py
index 07cefe39469..be6aab04c0e 100644
--- a/agent/curator_backup.py
+++ b/agent/curator_backup.py
@@ -15,7 +15,7 @@ import os
import re
import shutil
import tarfile
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from itertools import chain, count
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple
@@ -102,7 +102,7 @@ def _backup_cron_jobs_into(dest: Path) -> dict[str, Any]:
def _utc_id(now: Optional[datetime] = None) -> str:
"""UTC ISO-ish filesystem-safe timestamp: ``2026-05-01T13-05-42Z``."""
- s = (datetime.now(timezone.utc) if now is None else now).replace(microsecond=0).isoformat()
+ s = (datetime.now(UTC) if now is None else now).replace(microsecond=0).isoformat()
return s.removesuffix("+00:00").replace(":", "-") + "Z"
@@ -136,7 +136,7 @@ def _write_manifest(dest: Path, reason: str, archive_path: Path, skills_counted:
cron_jobs["reason"] = cron_info.get("reason", "not captured")
if cron_info.get("parse_warning"):
cron_jobs["parse_warning"] = cron_info["parse_warning"]
- manifest = {"id": dest.name, "reason": reason, "created_at": datetime.now(timezone.utc).isoformat(), "archive": archive_path.name,
+ manifest = {"id": dest.name, "reason": reason, "created_at": datetime.now(UTC).isoformat(), "archive": archive_path.name,
"archive_bytes": archive_path.stat().st_size, "skill_files": skills_counted, "cron_jobs": cron_jobs}
(dest / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8")
diff --git a/agent/estop.py b/agent/estop.py
index adf099697d0..b856b1231c2 100644
--- a/agent/estop.py
+++ b/agent/estop.py
@@ -14,7 +14,7 @@ import json
import logging
import threading
from contextlib import suppress
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Optional
@@ -64,7 +64,7 @@ def is_engaged() -> bool:
def engage(reason: Optional[str] = None) -> Path:
"""Create the ESTOP sentinel. Idempotent; re-engaging updates the file."""
path = sentinel_path()
- payload = {"engaged_at": datetime.now(timezone.utc).isoformat(), "reason": reason or None}
+ payload = {"engaged_at": datetime.now(UTC).isoformat(), "reason": reason or None}
try:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
diff --git a/agent/learning_graph.py b/agent/learning_graph.py
index 5dda45b0705..a7b15ed0528 100644
--- a/agent/learning_graph.py
+++ b/agent/learning_graph.py
@@ -13,7 +13,7 @@ import json
import re
from collections import Counter
from dataclasses import dataclass, field
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Optional
@@ -74,7 +74,7 @@ def _to_int_ts(value: Any) -> Optional[int]:
return int(float(s))
except ValueError:
parsed = datetime.fromisoformat(s)
- return int((parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=timezone.utc)).timestamp())
+ return int((parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)).timestamp())
except Exception:
return None
diff --git a/agent/learning_graph_render.py b/agent/learning_graph_render.py
index 2675e278402..e5ea25d5656 100644
--- a/agent/learning_graph_render.py
+++ b/agent/learning_graph_render.py
@@ -8,7 +8,7 @@ from __future__ import annotations
import math
from collections import Counter
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Iterable, Optional
from agent.learning_graph import memory_node_id
@@ -48,7 +48,7 @@ def _node_id(node: dict[str, Any]) -> str:
def _utc(ts: float) -> datetime:
- return datetime.fromtimestamp(ts, tz=timezone.utc)
+ return datetime.fromtimestamp(ts, tz=UTC)
def _lead_in(ratio: float) -> float:
diff --git a/agent/retry_utils.py b/agent/retry_utils.py
index 3ac54697805..1d35ccdb9e2 100644
--- a/agent/retry_utils.py
+++ b/agent/retry_utils.py
@@ -8,7 +8,7 @@ import random
import re
import threading
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from email.utils import parsedate_to_datetime
from typing import Any, Optional
@@ -60,8 +60,8 @@ def parse_retry_after_seconds(value_or_headers: Any) -> Optional[float]:
if when is None: # older stdlib returns None instead of raising
return None
if when.tzinfo is None:
- when = when.replace(tzinfo=timezone.utc)
- return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())
+ when = when.replace(tzinfo=UTC)
+ return max(0.0, (when - datetime.now(UTC)).total_seconds())
# Free-text "reset" grammars providers put in error bodies, tried in order. One table so the
diff --git a/agent/shell_hooks.py b/agent/shell_hooks.py
index 021d3795c31..8abbd2fc864 100644
--- a/agent/shell_hooks.py
+++ b/agent/shell_hooks.py
@@ -17,7 +17,7 @@ import threading
import time
from contextlib import ExitStack, contextmanager, suppress
from dataclasses import dataclass, field
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Callable, Dict, Iterator, List, Optional, Set, Tuple
@@ -73,7 +73,7 @@ def _entry_matches(e: Any, event: Optional[str], command: str) -> bool:
def _utc_now_iso() -> str:
- return datetime.now(tz=timezone.utc).isoformat().replace("+00:00", "Z")
+ return datetime.now(tz=UTC).isoformat().replace("+00:00", "Z")
def _payload_fields(kwargs: dict[str, Any]) -> dict[str, Any]:
@@ -641,7 +641,7 @@ def script_mtime_iso(command: str) -> Optional[str]:
mtime = os.path.getmtime(os.path.expanduser(path)) if path else None
except OSError:
return None
- return None if mtime is None else datetime.fromtimestamp(mtime, tz=timezone.utc).isoformat().replace("+00:00", "Z")
+ return None if mtime is None else datetime.fromtimestamp(mtime, tz=UTC).isoformat().replace("+00:00", "Z")
def script_is_executable(command: str) -> bool:
diff --git a/agent/trace_upload.py b/agent/trace_upload.py
index eb74eef5f29..d517caa5920 100644
--- a/agent/trace_upload.py
+++ b/agent/trace_upload.py
@@ -12,7 +12,7 @@ import json
import logging
import os
import uuid
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Dict, List, Optional, Tuple
logger = logging.getLogger(__name__)
@@ -43,7 +43,7 @@ class TraceRedactionError(RuntimeError):
# --- Conversion: Hermes OpenAI-format messages -> Claude Code JSONL ---
def _now_iso() -> str:
- return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
def _redact(text: Any, enabled: bool) -> Any:
diff --git a/agent/usage_pricing.py b/agent/usage_pricing.py
index 343bbfa3548..154df0d8151 100644
--- a/agent/usage_pricing.py
+++ b/agent/usage_pricing.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import logging
import re
from dataclasses import dataclass, fields, replace
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from decimal import Decimal
from typing import Any, Dict, Literal, Optional
@@ -133,7 +133,7 @@ class CostResult:
notes: tuple[str, ...] = ()
-_UTC_NOW = lambda: datetime.now(timezone.utc)
+_UTC_NOW = lambda: datetime.now(UTC)
_INCLUDED_ENTRY = PricingEntry(
input_cost_per_million=_ZERO, output_cost_per_million=_ZERO, cache_read_cost_per_million=_ZERO,
cache_write_cost_per_million=_ZERO, source="none", pricing_version="included-route",
diff --git a/agent/vault_store.py b/agent/vault_store.py
index 11324489fa1..55f1851c878 100644
--- a/agent/vault_store.py
+++ b/agent/vault_store.py
@@ -24,7 +24,7 @@ import threading
import uuid
from contextlib import contextmanager, suppress
from dataclasses import dataclass
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Dict, List, Optional
from urllib.parse import urlsplit
@@ -358,7 +358,7 @@ class VaultStore:
"kind": kind,
"label": label,
"origin": norm_origin,
- "created_at": datetime.now(timezone.utc).isoformat(),
+ "created_at": datetime.now(UTC).isoformat(),
"identifier_type": identifier_type,
"identifier": identifier,
"secret": dict(secret),
diff --git a/agent/verification_evidence.py b/agent/verification_evidence.py
index 3cbdef7ebfc..cfba00c07e9 100644
--- a/agent/verification_evidence.py
+++ b/agent/verification_evidence.py
@@ -11,7 +11,7 @@ import sqlite3
import tempfile
import threading
from dataclasses import dataclass
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
from typing import Any, Optional
@@ -112,7 +112,7 @@ class VerificationEvidence:
def _utc_now() -> str:
- return datetime.now(timezone.utc).isoformat()
+ return datetime.now(UTC).isoformat()
def _db_path() -> Path:
@@ -372,7 +372,7 @@ def _prune_old_events(conn: sqlite3.Connection, *, session_id: str, root: str) -
old events and cap the total — never dropping an event still referenced
by a ``verification_state.last_event_id``.
"""
- cutoff = (datetime.now(timezone.utc) - timedelta(days=_MAX_EVIDENCE_AGE_DAYS)).isoformat()
+ cutoff = (datetime.now(UTC) - timedelta(days=_MAX_EVIDENCE_AGE_DAYS)).isoformat()
conn.execute(
"DELETE FROM verification_events WHERE session_id = ? AND root = ? AND id NOT IN ("
" SELECT id FROM verification_events WHERE session_id = ? AND root = ?"
diff --git a/agent/verify/environment.py b/agent/verify/environment.py
index 644ebb4145a..a43d45f81be 100644
--- a/agent/verify/environment.py
+++ b/agent/verify/environment.py
@@ -8,7 +8,7 @@ when present and valid it wins over fresh static detection.
from __future__ import annotations
import json
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from agent.verify.recipes import Recipe, detect_recipe
@@ -37,7 +37,7 @@ def save_manifest(root: Path, recipe: Recipe) -> Path:
"""Persist ``recipe`` in the versioned wrapper shape; returns the manifest path."""
path = manifest_path(root)
path.parent.mkdir(parents=True, exist_ok=True)
- payload = {"version": MANIFEST_VERSION, "recipe": recipe.to_dict(), "updatedAt": datetime.now(timezone.utc).isoformat()}
+ payload = {"version": MANIFEST_VERSION, "recipe": recipe.to_dict(), "updatedAt": datetime.now(UTC).isoformat()}
path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
return path
diff --git a/apps/desktop/electron/pool-retirement-live-fixture/serve.py b/apps/desktop/electron/pool-retirement-live-fixture/serve.py
index a3e88aab4da..b1c58e540ed 100644
--- a/apps/desktop/electron/pool-retirement-live-fixture/serve.py
+++ b/apps/desktop/electron/pool-retirement-live-fixture/serve.py
@@ -6,7 +6,7 @@ cron ledgers, session-token auth, and uvicorn shutdown are production code.
import asyncio
from contextlib import asynccontextmanager
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
import os
from pathlib import Path
import shutil
@@ -26,7 +26,7 @@ if sys.argv[2] == "cron-busy":
scripts.mkdir(parents=True)
shutil.copyfile(Path(__file__).with_name("cron_work.py"), scripts / "cron_work.py")
job = create_job(
- prompt=None, schedule=datetime.now(timezone.utc).isoformat(),
+ prompt=None, schedule=datetime.now(UTC).isoformat(),
name="Native pool retirement work", script="cron_work.py", no_agent=True,
deliver="local", repeat=1, workdir=str(home),
)
diff --git a/cron/jobs.py b/cron/jobs.py
index da16cfcbe0b..7d165965189 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -26,7 +26,7 @@ try:
import msvcrt
except ImportError: # pragma: no cover - non-Windows
msvcrt = None
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
from hermes_constants import get_hermes_home
from cron.constants import CLAIM_TTL_INACTIVITY_HEADROOM, FIRE_CLAIM_SKEW_SECONDS, FIRE_CLAIM_TTL_SECONDS
@@ -845,7 +845,7 @@ def parse_schedule(schedule: str) -> dict[str, Any]:
f"Invalid duration '{duration_str}' after 'in '. Use e.g. 'in 30m', 'in 2h'.")
now = _hermes_now()
# Durations measure elapsed time, not wall-clock hours across a DST transition.
- run_at = (now.astimezone(timezone.utc) + timedelta(minutes=minutes)).astimezone(now.tzinfo)
+ run_at = (now.astimezone(UTC) + timedelta(minutes=minutes)).astimezone(now.tzinfo)
return {"kind": "once", "run_at": run_at.isoformat(), "display": f"once in {duration_str}"}
with contextlib.suppress(ValueError):
return _interval_schedule(parse_duration(schedule))
@@ -872,28 +872,28 @@ def _ensure_aware(dt: datetime) -> datetime:
def _elapsed_seconds(later: datetime, earlier: datetime) -> float:
"""Return elapsed seconds between aware instants, independent of wall time."""
- return (later.astimezone(timezone.utc) - earlier.astimezone(timezone.utc)).total_seconds()
+ return (later.astimezone(UTC) - earlier.astimezone(UTC)).total_seconds()
def _instant_after(left: datetime, right: datetime) -> bool:
"""Whether *left* is a later absolute instant than *right*."""
- return left.astimezone(timezone.utc) > right.astimezone(timezone.utc)
+ return left.astimezone(UTC) > right.astimezone(UTC)
def _instant_at_or_before(left: datetime, right: datetime) -> bool:
"""Whether *left* is at or before *right* as an absolute instant."""
- return left.astimezone(timezone.utc) <= right.astimezone(timezone.utc)
+ return left.astimezone(UTC) <= right.astimezone(UTC)
def _instant_before(left: datetime, right: datetime) -> bool:
"""Whether *left* is an earlier absolute instant than *right*."""
- return left.astimezone(timezone.utc) < right.astimezone(timezone.utc)
+ return left.astimezone(UTC) < right.astimezone(UTC)
def _seconds_after(dt: datetime, seconds: float) -> datetime:
"""*dt* plus real *seconds*, in *dt*'s zone. Aware ``+ timedelta`` is wall-clock arithmetic
that drops ``fold``, so inside a fall-back hour it lands an hour off."""
- return (dt.astimezone(timezone.utc) + timedelta(seconds=seconds)).astimezone(dt.tzinfo)
+ return (dt.astimezone(UTC) + timedelta(seconds=seconds)).astimezone(dt.tzinfo)
def _parse_aware(value: Any) -> Optional[datetime]:
@@ -1190,7 +1190,7 @@ def compute_next_run(schedule: dict[str, Any], last_run_at: Optional[str] = None
if minutes is None:
return None
# Add in UTC so an interval keeps its duration when the profile's UTC offset changes.
- next_run = base_time.astimezone(timezone.utc) + timedelta(minutes=minutes)
+ next_run = base_time.astimezone(UTC) + timedelta(minutes=minutes)
return next_run.astimezone(base_time.tzinfo).isoformat()
if kind == "cron":
expr = schedule.get("expr")
diff --git a/cron/occurrences.py b/cron/occurrences.py
index 1ff4276e6e6..23c7eed0f68 100644
--- a/cron/occurrences.py
+++ b/cron/occurrences.py
@@ -1,6 +1,6 @@
"""Exact scheduled identities, independent of mutable jobs.json dispatch stamps, plus the
profile-local stale-schedule catch-up counter marker."""
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
import logging
logger = logging.getLogger(__name__)
@@ -14,7 +14,7 @@ def scheduled_instant(value):
instant = datetime.fromisoformat(value)
if instant.tzinfo is None:
return None
- return instant.astimezone(timezone.utc).isoformat()
+ return instant.astimezone(UTC).isoformat()
except ValueError:
return None
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 1eea681c8e1..bd715ff3083 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -18,7 +18,7 @@ import threading
import time
import uuid
from dataclasses import dataclass
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
# fcntl is Unix-only; Windows uses msvcrt
try:
@@ -1257,7 +1257,7 @@ def _usage_audit_path() -> Path:
def _utcnow_iso_ms() -> str:
"""RFC3339 UTC timestamp with millisecond precision and 'Z' suffix."""
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
return now.strftime("%Y-%m-%dT%H:%M:%S.") + f"{now.microsecond // 1000:03d}Z"
diff --git a/evals/postmortem/review_probes/credential_identity_probe.py b/evals/postmortem/review_probes/credential_identity_probe.py
index a0327b6094d..ad2aa58e449 100644
--- a/evals/postmortem/review_probes/credential_identity_probe.py
+++ b/evals/postmortem/review_probes/credential_identity_probe.py
@@ -6,7 +6,7 @@ from the command line / environment, never hard-coded. Usage: see the argument p
"""
import os, tempfile, sys, json, time, base64, threading, importlib.util
from pathlib import Path
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
ROOT = Path(sys.argv[1]); MODE = sys.argv[2]
sys.path.insert(0, str(ROOT))
@@ -55,7 +55,7 @@ if MODE=='main':
spec=importlib.util.spec_from_file_location('main_prep',Path(__file__).with_name('main-turn_iteration_prep.py')); mod=importlib.util.module_from_spec(spec);sys.modules[spec.name]=mod;spec.loader.exec_module(mod);prepare_iteration=mod.prepare_iteration
def store(token):
- exp=claims(token)['exp']; state={'portal_base_url':'https://portal.nousresearch.com','inference_base_url':'https://inference-api.nousresearch.com/v1','client_id':'hermes-cli','token_type':'Bearer','scope':'inference:invoke','access_token':token,'refresh_token':'fixture-refresh-never-send','expires_at':datetime.fromtimestamp(exp,timezone.utc).isoformat(),'expires_in':3600,'agent_key':token,'agent_key_expires_at':datetime.fromtimestamp(exp,timezone.utc).isoformat()}
+ exp=claims(token)['exp']; state={'portal_base_url':'https://portal.nousresearch.com','inference_base_url':'https://inference-api.nousresearch.com/v1','client_id':'hermes-cli','token_type':'Bearer','scope':'inference:invoke','access_token':token,'refresh_token':'fixture-refresh-never-send','expires_at':datetime.fromtimestamp(exp,UTC).isoformat(),'expires_in':3600,'agent_key':token,'agent_key_expires_at':datetime.fromtimestamp(exp,UTC).isoformat()}
(home/'hermes'/'auth.json').write_text(json.dumps({'version':1,'active_provider':'nous','providers':{'nous':state}}), encoding='utf-8')
results=[]
for case, own_sub, store_sub, ttl in [('same-account','account-A','account-A',30),('explicit-account','account-A','account-B',30),('far-from-expiry','account-A','account-B',3000)]:
diff --git a/gateway/drain_control.py b/gateway/drain_control.py
index 3618498d39f..7aa6ce6ae1c 100644
--- a/gateway/drain_control.py
+++ b/gateway/drain_control.py
@@ -16,7 +16,7 @@ import contextlib
import functools
import json
import logging
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Optional
@@ -73,7 +73,7 @@ def write_drain_request(
copy surviving a machine restart on the durable volume reads as stale.
"""
payload = {
- "action": "drain", "requested_at": datetime.now(timezone.utc).isoformat(), "principal": principal,
+ "action": "drain", "requested_at": datetime.now(UTC).isoformat(), "principal": principal,
"epoch": current_instantiation_epoch(), "suppress_notification": bool(suppress_notification),
}
atomic_json_write(drain_request_path(home), payload)
@@ -105,7 +105,7 @@ def _marker_is_expired(body: dict[str, Any]) -> bool:
requested_at = _parse_iso(raw)
if requested_at is None:
return False
- age = (datetime.now(timezone.utc) - requested_at).total_seconds()
+ age = (datetime.now(UTC) - requested_at).total_seconds()
if age <= DRAIN_REQUEST_MAX_AGE_SECONDS:
return False
if _expiry_logged_for != raw:
diff --git a/gateway/host_rendezvous.py b/gateway/host_rendezvous.py
index a71ea28a56e..cf2db2bf285 100644
--- a/gateway/host_rendezvous.py
+++ b/gateway/host_rendezvous.py
@@ -41,7 +41,7 @@ import os
import stat
import sys
from dataclasses import dataclass
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Optional, Sequence
@@ -490,7 +490,7 @@ def publish_record(
protocol_version=HOST_PROTOCOL_VERSION,
token_fingerprint=token_fingerprint(token or ""),
profiles=tuple(str(p) for p in profiles),
- updated_at=datetime.now(timezone.utc).isoformat(),
+ updated_at=datetime.now(UTC).isoformat(),
home=str(home or ""),
)
try:
diff --git a/gateway/lifecycle_ledger.py b/gateway/lifecycle_ledger.py
index aac42bd66b4..e39c3c38eba 100644
--- a/gateway/lifecycle_ledger.py
+++ b/gateway/lifecycle_ledger.py
@@ -17,7 +17,7 @@ import os
import sqlite3
import time
from contextlib import closing
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Dict, Optional
@@ -42,7 +42,7 @@ def get_lifecycle_sentinel_path(home: Optional[Path] = None) -> Path:
def _now_iso() -> str:
- return datetime.now(timezone.utc).isoformat()
+ return datetime.now(UTC).isoformat()
def _proc_fields(path: str, wanted: dict[str, str]) -> dict[str, int]:
diff --git a/gateway/memory_status.py b/gateway/memory_status.py
index 31b87b92e53..84d84273abc 100644
--- a/gateway/memory_status.py
+++ b/gateway/memory_status.py
@@ -9,7 +9,7 @@ coarse numbers (MB), enums and booleans. A missing/corrupt file degrades to
from __future__ import annotations
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Dict, Optional
@@ -44,7 +44,7 @@ def _parse_iso(value: Any) -> Optional[datetime]:
parsed = datetime.fromisoformat(value) if isinstance(value, str) and value else None
except ValueError:
return None
- return parsed.replace(tzinfo=timezone.utc) if parsed is not None and parsed.tzinfo is None else parsed
+ return parsed.replace(tzinfo=UTC) if parsed is not None and parsed.tzinfo is None else parsed
def classify_pressure(available_kib: Any, total_kib: Any) -> str:
@@ -79,7 +79,7 @@ def collect_memory_status(
"""``memory`` block for ``/api/status``; ``home`` scopes to a profile (``None`` =
active), ``now`` is injectable. Never raises — a down gateway or corrupt files
yield ``pressure="unknown"`` plus whatever fields could be recovered."""
- moment = now or datetime.now(timezone.utc)
+ moment = now or datetime.now(UTC)
status: dict[str, Any] = {
"pressure": "unknown", "gateway_rss_mb": None, "system_total_mb": None, "system_available_mb": None,
"swap_used_mb": None, "sampled_at": None, "last_boot_unclean": False, "last_boot_suspected_oom": False,
diff --git a/gateway/message_timestamps.py b/gateway/message_timestamps.py
index 653eaf04057..3e7800af9dd 100644
--- a/gateway/message_timestamps.py
+++ b/gateway/message_timestamps.py
@@ -11,7 +11,7 @@ import errno
import re
import sys
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Optional, Tuple
from hermes_time import safe_strftime
@@ -107,7 +107,7 @@ def format_message_timestamp(ts_value: Any, tz=None) -> str:
try:
# An early positive epoch can fall in 1969 locally. Starting from aware
# UTC avoids Windows' negative-time fold probe in naive astimezone().
- dt = datetime.fromtimestamp(epoch, tz=tz) if tz is not None else datetime.fromtimestamp(epoch, tz=timezone.utc).astimezone()
+ dt = datetime.fromtimestamp(epoch, tz=tz) if tz is not None else datetime.fromtimestamp(epoch, tz=UTC).astimezone()
except (OSError, OverflowError, ValueError):
return ""
return f"[{safe_strftime(dt, '%a %Y-%m-%d %H:%M:%S %Z')}]"
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index fa4b8860090..7db0bdd156e 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -24,7 +24,7 @@ import sys
import threading
import time
import uuid
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
@@ -1380,7 +1380,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
def _iso_timestamp(timestamp: Optional[float]) -> Optional[str]:
if timestamp is None:
return None
- return datetime.fromtimestamp(timestamp, timezone.utc).isoformat()
+ return datetime.fromtimestamp(timestamp, UTC).isoformat()
def _reset_metrics_if_needed(self) -> None:
current_day = self._metrics_day_key()
diff --git a/gateway/platforms/qqbot/adapter.py b/gateway/platforms/qqbot/adapter.py
index e15c0611af4..0c5b74542c9 100644
--- a/gateway/platforms/qqbot/adapter.py
+++ b/gateway/platforms/qqbot/adapter.py
@@ -19,7 +19,7 @@ import os
import re
import time
import uuid
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple
from urllib.parse import urlparse
@@ -1670,5 +1670,5 @@ class QQAdapter(OwnAccessPolicyMixin, BasePlatformAdapter):
with contextlib.suppress(ValueError, TypeError):
return datetime.fromisoformat(raw)
with contextlib.suppress(ValueError, TypeError):
- return datetime.fromtimestamp(int(raw) / 1000, tz=timezone.utc)
- return datetime.now(tz=timezone.utc)
+ return datetime.fromtimestamp(int(raw) / 1000, tz=UTC)
+ return datetime.now(tz=UTC)
diff --git a/gateway/platforms/signal.py b/gateway/platforms/signal.py
index f94fb881be9..c1d7f0f6718 100644
--- a/gateway/platforms/signal.py
+++ b/gateway/platforms/signal.py
@@ -16,7 +16,7 @@ import time
import uuid
from collections import OrderedDict
from contextlib import suppress
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import quote, unquote
@@ -475,10 +475,10 @@ class SignalAdapter(BasePlatformAdapter):
(mt for prefix, mt in _MEDIA_TYPE_BY_MIME_PREFIX if any(m.startswith(prefix) for m in media_types)),
MessageType.DOCUMENT)
ts_ms = envelope_data.get("timestamp", 0) # milliseconds since epoch
- timestamp = datetime.now(tz=timezone.utc)
+ timestamp = datetime.now(tz=UTC)
if ts_ms:
with suppress(ValueError, OSError):
- timestamp = datetime.fromtimestamp(ts_ms / 1000, tz=timezone.utc)
+ timestamp = datetime.fromtimestamp(ts_ms / 1000, tz=UTC)
# raw_message keeps sender + timestamp_ms so processing hooks can build sendReaction targets.
event = MessageEvent(
source=source, text=text or "", message_type=msg_type, media_urls=media_urls,
diff --git a/gateway/platforms/yuanbao.py b/gateway/platforms/yuanbao.py
index 1a8459c34ac..c7559d2a6da 100644
--- a/gateway/platforms/yuanbao.py
+++ b/gateway/platforms/yuanbao.py
@@ -26,7 +26,7 @@ import urllib.parse
import uuid
from abc import ABC, abstractmethod
from dataclasses import dataclass, field as dc_field
-from datetime import datetime, timezone, timedelta
+from datetime import datetime, timezone, timedelta, UTC
from enum import Enum
from pathlib import Path
from typing import Any, Callable, ClassVar, Dict, Iterator, List, Optional, Tuple
@@ -671,7 +671,7 @@ class RecallGuardMiddleware(InboundMiddleware):
return
# Branch B: not found in transcript → append system note
store.append_to_transcript(sid, {
- "role": "system", "timestamp": datetime.now(tz=timezone.utc).isoformat(),
+ "role": "system", "timestamp": datetime.now(tz=UTC).isoformat(),
"content": f'[recall] message_id="{recalled_id}" has been recalled; do not quote or reference it.',
})
logger.info("[%s] Recall: system note for msg_id=%s (branch B)", adapter.name, recalled_id)
@@ -1103,7 +1103,7 @@ class GroupAtGuardMiddleware(InboundMiddleware):
body_text = f"{text}\n{summary}" if text else summary
entry: dict = {
"role": "user", "content": f"[{sender_display}|{source.user_id or 'unknown'}]\n{body_text}",
- "timestamp": datetime.now(tz=timezone.utc).isoformat(), "observed": True,
+ "timestamp": datetime.now(tz=UTC).isoformat(), "observed": True,
}
if msg_id:
entry["message_id"] = msg_id
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.py
index 192357f31c2..2afc4b47f7c 100644
--- a/gateway/run_adapters.py
+++ b/gateway/run_adapters.py
@@ -18,7 +18,7 @@ import time
import weakref as _weakref
from agent.async_utils import consume_detached_task_result
from contextvars import Context
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from gateway.config import (
ON_ALL_ADAPTERS_DOWN_POLICIES,
SHARED_LISTENER_MIRROR_PLATFORMS,
@@ -753,7 +753,7 @@ class GatewayAdapterLifecycleMixin:
)
self._update_platform_runtime_status(
status_key or platform.value, platform_state="retrying", needs_attention=True,
- retrying_since=(datetime.now(timezone.utc) - timedelta(seconds=queued_for)).isoformat(),
+ retrying_since=(datetime.now(UTC) - timedelta(seconds=queued_for)).isoformat(),
)
def _mark_platform_fatal(self, status_key: str, adapter) -> None:
diff --git a/gateway/session_lifecycle.py b/gateway/session_lifecycle.py
index 6327e6272b4..3f13ced6319 100644
--- a/gateway/session_lifecycle.py
+++ b/gateway/session_lifecycle.py
@@ -6,7 +6,7 @@ import logging
import os
import time
import uuid
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from typing import TYPE_CHECKING, Optional
from hermes_state_ids import new_session_id
@@ -148,7 +148,7 @@ class SessionLifecycleMixin:
return None
# Aware UTC, unlike the local wall clock elsewhere: the next process compares it with
# epoch transcript timestamps and may run in another zone (DST, container vs unit TZ).
- self._set_turn_marker_locked(session_key, entry, token, datetime.now(timezone.utc))
+ self._set_turn_marker_locked(session_key, entry, token, datetime.now(UTC))
return token
def clear_turn_active(self, session_key: str, token: str) -> bool:
diff --git a/gateway/shutdown_watchdog.py b/gateway/shutdown_watchdog.py
index 86a21e65348..60a6888d201 100644
--- a/gateway/shutdown_watchdog.py
+++ b/gateway/shutdown_watchdog.py
@@ -18,7 +18,7 @@ import os
import sys
import threading
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Callable, Dict, Optional
@@ -212,7 +212,7 @@ def write_loop_heartbeat(
``start_time`` (process start, epoch seconds) lets supervisors detect PID reuse."""
path = get_loop_heartbeat_path(home)
payload: dict[str, Any] = {"pid": int(pid if pid is not None else os.getpid()),
- "updated_at": datetime.now(timezone.utc).isoformat(),
+ "updated_at": datetime.now(UTC).isoformat(),
"monotonic": time.monotonic()}
if start_time is not None:
payload["start_time"] = float(start_time)
@@ -244,7 +244,7 @@ def _write_watchdog_dump(dump_path: Path, *, delay_s: float,
except OSError:
return
header = {"event": "shutdown_watchdog_fired", "pid": os.getpid(), "delay_s": delay_s,
- "fired_at": datetime.now(timezone.utc).isoformat(), "snapshot": snapshot or {}}
+ "fired_at": datetime.now(UTC).isoformat(), "snapshot": snapshot or {}}
with contextlib.suppress(Exception), open(dump_path, "a", encoding="utf-8") as fh:
fh.write(json.dumps(header, default=str) + "\n--- faulthandler dump (all threads) ---\n")
fh.flush()
diff --git a/gateway/status.py b/gateway/status.py
index 7564c0438bf..f963b69f7e4 100644
--- a/gateway/status.py
+++ b/gateway/status.py
@@ -17,7 +17,7 @@ import sys
import threading
import time
from dataclasses import dataclass
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Callable, NamedTuple, Optional
@@ -208,7 +208,7 @@ def record_start_and_check_storm(
try:
path = get_hermes_home() / "gateway-starts.log"
path.parent.mkdir(parents=True, exist_ok=True)
- now = datetime.now(timezone.utc).timestamp()
+ now = datetime.now(UTC).timestamp()
existing: list[float] = []
if path.exists():
for line in path.read_text(encoding="utf-8-sig").splitlines():
@@ -336,7 +336,7 @@ def _get_lock_dir() -> Path:
def _utc_now_iso() -> str:
- return datetime.now(timezone.utc).isoformat()
+ return datetime.now(UTC).isoformat()
# Epochs before 2000-01-01 are corrupt/hand-edited state (e.g. an accidental 0).
@@ -357,14 +357,14 @@ def normalize_updated_at(value: Any) -> Optional[str]:
parsed = datetime.fromisoformat(raw)
except ValueError:
return None
- return (parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)).isoformat()
+ return (parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)).isoformat()
if isinstance(value, (int, float)) and not isinstance(value, bool):
seconds = float(value)
- now = datetime.now(timezone.utc).timestamp()
+ now = datetime.now(UTC).timestamp()
if not math.isfinite(seconds) or seconds < _EPOCH_MIN_PLAUSIBLE or seconds > now + 86400:
return None
try:
- return datetime.fromtimestamp(seconds, tz=timezone.utc).isoformat()
+ return datetime.fromtimestamp(seconds, tz=UTC).isoformat()
except (OverflowError, OSError, ValueError):
return None
return None
@@ -1240,7 +1240,7 @@ def runtime_status_heartbeat_age_s(record: Optional[dict[str, Any]]) -> Optional
updated_at = normalize_updated_at(record.get("updated_at")) if isinstance(record, dict) else None
if not updated_at:
return None
- return max(0, int((datetime.now(timezone.utc) - datetime.fromisoformat(updated_at)).total_seconds()))
+ return max(0, int((datetime.now(UTC) - datetime.fromisoformat(updated_at)).total_seconds()))
def runtime_status_pid_is_live(record: Optional[dict[str, Any]]) -> bool:
@@ -1665,7 +1665,7 @@ def _get_planned_stop_marker_path() -> Path:
def _marker_is_stale(written_at: str, ttl_s: int) -> bool:
try:
- age = datetime.now(timezone.utc) - datetime.fromisoformat(written_at)
+ age = datetime.now(UTC) - datetime.fromisoformat(written_at)
return age.total_seconds() > ttl_s
except (TypeError, ValueError):
return True
diff --git a/hermes_cli/anon_auth.py b/hermes_cli/anon_auth.py
index 972471ca35c..45c9aadd996 100644
--- a/hermes_cli/anon_auth.py
+++ b/hermes_cli/anon_auth.py
@@ -28,7 +28,7 @@ import math
import os
import time
from dataclasses import dataclass
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from typing import Any, Callable, Dict, Optional
from agent.retry_utils import parse_retry_after_seconds
@@ -394,10 +394,10 @@ def apply_exchange_to_state(state: dict[str, Any], exchanged: dict[str, Any]) ->
from hermes_cli.auth_nous import _validate_nous_inference_url_from_network
access_token = exchanged["access_token"]
claims = _decode_jwt_claims(access_token)
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
exp = claims.get("exp")
if isinstance(exp, (int, float)):
- expires_at = datetime.fromtimestamp(float(exp), tz=timezone.utc)
+ expires_at = datetime.fromtimestamp(float(exp), tz=UTC)
else:
expires_at = now + timedelta(seconds=int(exchanged.get("expires_in") or 900))
# NAS names the welcome host on every exchange; absent (older NAS) or outside the allowlist
@@ -1019,7 +1019,7 @@ def _account_state_from_token(
"""The ``providers.nous`` shape for the signed-in account (same fields the device-code login writes)."""
from hermes_cli.auth import PROVIDER_REGISTRY, _coerce_ttl_seconds, _optional_base_url, _tls_state_from_verify
from hermes_cli.auth_nous import _NOUS_EMPTY_AGENT_KEY_FIELDS, _iso_after, refresh_nous_oauth_from_state
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
ttl = _coerce_ttl_seconds(token_data.get("expires_in", 0))
inference_url = (
_optional_base_url(token_data.get("inference_base_url"))
diff --git a/hermes_cli/auth.py b/hermes_cli/auth.py
index 3f1e8e53075..d1dec24769e 100644
--- a/hermes_cli/auth.py
+++ b/hermes_cli/auth.py
@@ -25,7 +25,7 @@ import webbrowser
from contextlib import ExitStack, contextmanager
from dataclasses import dataclass, field
from functools import partial
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Callable, Dict, FrozenSet, Iterable, List, Optional, Tuple
from urllib.parse import urlparse
@@ -798,7 +798,7 @@ def _save_auth_store(auth_store: dict[str, Any], target_path: Optional[Path] = N
an explicit *target_path* (e.g. the global-root write-through for rotating xAI OAuth grants)."""
auth_file = target_path if target_path is not None else _auth_file_path()
auth_store["version"] = AUTH_STORE_VERSION
- auth_store["updated_at"] = datetime.now(timezone.utc).isoformat()
+ auth_store["updated_at"] = datetime.now(UTC).isoformat()
_save_private_json(auth_file, auth_store, fsync_dir=True)
if target_path is not None:
# A write-through to the global root must not be masked by the mtime memo: on coarse-mtime
@@ -1724,7 +1724,7 @@ def resolve_provider(
def _utc_now_z() -> str:
"""Current UTC time as an ISO-8601 string with a ``Z`` suffix (last_refresh format)."""
- return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+ return datetime.now(UTC).isoformat().replace("+00:00", "Z")
def _parse_iso_timestamp(value: Any) -> Optional[float]:
@@ -1738,7 +1738,7 @@ def _parse_iso_timestamp(value: Any) -> Optional[float]:
except Exception:
return None
if parsed.tzinfo is None:
- parsed = parsed.replace(tzinfo=timezone.utc)
+ parsed = parsed.replace(tzinfo=UTC)
return parsed.timestamp()
@@ -1759,7 +1759,7 @@ def _last_auth_error_marker(
return {
"provider": provider, "message": str(error), "reason": reason, "relogin_required": True,
"code": error.code if default_code is None else (error.code or default_code),
- "at": datetime.now(timezone.utc).isoformat()}
+ "at": datetime.now(UTC).isoformat()}
_FLAT_OAUTH_TOKEN_KEYS = ("access_token", "refresh_token", "expires_at", "expires_in", "obtained_at")
diff --git a/hermes_cli/auth_minimax.py b/hermes_cli/auth_minimax.py
index f17bf98a6ec..ca7cbf185c8 100644
--- a/hermes_cli/auth_minimax.py
+++ b/hermes_cli/auth_minimax.py
@@ -12,7 +12,7 @@ import hashlib
import json
import time
import uuid
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Callable, Dict, Optional, TYPE_CHECKING
from hermes_cli.auth_constants import (
AuthError, MINIMAX_OAUTH_GRANT_TYPE, MINIMAX_OAUTH_REFRESH_SKEW_SECONDS, MINIMAX_OAUTH_SCOPE,
@@ -105,11 +105,11 @@ def _minimax_resolve_token_expiry_unix(expired_in: int, *, now: datetime) -> flo
def _minimax_expiry_fields(expired_in: Any) -> dict[str, Any]:
"""``obtained_at`` / ``expires_at`` / ``expires_in`` derived from a MiniMax ``expired_in``."""
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
expires_at_unix = _minimax_resolve_token_expiry_unix(int(expired_in), now=now)
return {
"obtained_at": now.isoformat(),
- "expires_at": datetime.fromtimestamp(expires_at_unix, tz=timezone.utc).isoformat(),
+ "expires_at": datetime.fromtimestamp(expires_at_unix, tz=UTC).isoformat(),
"expires_in": max(0, int(expires_at_unix - now.timestamp())),
}
@@ -119,7 +119,7 @@ def _minimax_poll_token(
user_code: str, code_verifier: str, expired_in: int, interval_ms: Optional[int],
) -> dict[str, Any]:
# expired_in is a unix-ms timestamp upstream (OpenClaw) but small values are TTL seconds.
- deadline = _minimax_resolve_token_expiry_unix(expired_in, now=datetime.now(timezone.utc))
+ deadline = _minimax_resolve_token_expiry_unix(expired_in, now=datetime.now(UTC))
interval = max(2.0, (interval_ms or 2000) / 1000.0)
while time.time() < deadline:
diff --git a/hermes_cli/auth_nous.py b/hermes_cli/auth_nous.py
index 768a3189d27..8d363e526fb 100644
--- a/hermes_cli/auth_nous.py
+++ b/hermes_cli/auth_nous.py
@@ -14,7 +14,7 @@ import threading
import time
import uuid
from contextlib import contextmanager, suppress
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, FrozenSet, List, Optional
from urllib.parse import urlparse
@@ -67,7 +67,7 @@ def _oauth_trace(event: str, *, sequence_id: Optional[str] = None, **fields: Any
def _iso_after(now: datetime, ttl_seconds: int) -> str:
"""ISO timestamp *ttl_seconds* after *now* (UTC)."""
- return datetime.fromtimestamp(now.timestamp() + ttl_seconds, tz=timezone.utc).isoformat()
+ return datetime.fromtimestamp(now.timestamp() + ttl_seconds, tz=UTC).isoformat()
# Nous agent-key slots; a fresh login persists them as None, quarantine strips them.
@@ -297,7 +297,7 @@ def _nous_jwt_expires_at(token: Any, fallback_expires_at: Any = None) -> Optiona
exp = claims.get("exp")
if isinstance(exp, (int, float)):
with suppress(Exception):
- return datetime.fromtimestamp(float(exp), tz=timezone.utc).isoformat()
+ return datetime.fromtimestamp(float(exp), tz=UTC).isoformat()
return fallback_expires_at if isinstance(fallback_expires_at, str) else None
@@ -310,7 +310,7 @@ def _set_nous_agent_key_from_invoke_jwt(
existing_obtained_at = state.get("agent_key_obtained_at")
if not obtained_at:
reuse = state.get("agent_key") == access_token and _nonempty_str(existing_obtained_at)
- obtained_at = existing_obtained_at if reuse else datetime.now(timezone.utc).isoformat()
+ obtained_at = existing_obtained_at if reuse else datetime.now(UTC).isoformat()
expires_at = _nous_jwt_expires_at(access_token, state.get("expires_at"))
expires_in = _remaining_ttl(expires_at, state.get("expires_in"))
if expires_at:
@@ -460,7 +460,7 @@ def _write_shared_nous_state(state: dict[str, Any]) -> None:
return
shared = {
"_schema": 1, **_nous_shared_shape(state),
- "updated_at": datetime.now(timezone.utc).isoformat()}
+ "updated_at": datetime.now(UTC).isoformat()}
try:
with _nous_shared_store_lock():
path = _nous_shared_store_path()
@@ -536,8 +536,8 @@ def _quarantine_forensics(state: dict[str, Any], error: AuthError, reason: str)
if isinstance(expires_at_raw, str) and expires_at_raw:
try:
parsed = datetime.fromisoformat(expires_at_raw)
- already_expired = (parsed.replace(tzinfo=parsed.tzinfo or timezone.utc)
- < datetime.now(timezone.utc))
+ already_expired = (parsed.replace(tzinfo=parsed.tzinfo or UTC)
+ < datetime.now(UTC))
except ValueError:
already_expired = None
forensic["token_already_expired"] = already_expired
@@ -706,7 +706,7 @@ def _apply_nous_refreshed_tokens(
the rotated tokens (key order in auth.json is preserved from the original login shape).
"""
from hermes_cli.auth import _coerce_ttl_seconds
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
access_ttl = _coerce_ttl_seconds(refreshed.get("expires_in"))
state["access_token"] = refreshed["access_token"]
state["refresh_token"] = refreshed.get("refresh_token") or refresh_token
@@ -1420,7 +1420,7 @@ def _nous_device_code_login(
client=client, portal_base_url=portal_base_url, client_id=client_id,
device_code=str(device_data["device_code"]), expires_in=expires_in,
poll_interval=interval)
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
token_expires_in = _coerce_ttl_seconds(token_data.get("expires_in", 0))
resolved_inference_url = (
_optional_base_url(token_data.get("inference_base_url")) or requested_inference_url)
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.py
index 0ae83ef92b8..c109b948ada 100644
--- a/hermes_cli/backup.py
+++ b/hermes_cli/backup.py
@@ -13,7 +13,7 @@ import time
import zipfile
import zlib
from contextlib import contextmanager, suppress
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple
@@ -1260,7 +1260,7 @@ def _create_quick_snapshot_locked(
)
return True
- ts = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
+ ts = datetime.now(UTC).strftime("%Y%m%d-%H%M%S")
base_snap_id = f"{ts}-{label}" if label else ts
snap_id = base_snap_id
suffix = 2
diff --git a/hermes_cli/backup_sqlite.py b/hermes_cli/backup_sqlite.py
index 1f0177b1db4..f0c2d2f1ad7 100644
--- a/hermes_cli/backup_sqlite.py
+++ b/hermes_cli/backup_sqlite.py
@@ -11,7 +11,7 @@ import sys
import tempfile
import time
from contextlib import suppress
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Optional
@@ -86,7 +86,7 @@ def preflight_state_db(home: Path) -> dict:
if not source.exists():
return {"path": None, "message": "state.db not found (fresh install?)"}
prefix = "state.db.pre-update-emergency-"
- stamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H-%M-%S-%fZ")
+ stamp = datetime.now(UTC).strftime("%Y-%m-%dT%H-%M-%S-%fZ")
destination = home / f"{prefix}{stamp}-{os.getpid()}.bak"
fd, name = tempfile.mkstemp(prefix=prefix, suffix=".partial", dir=home)
os.close(fd)
diff --git a/hermes_cli/cron.py b/hermes_cli/cron.py
index d213dbe3f8c..6e134b35cf4 100644
--- a/hermes_cli/cron.py
+++ b/hermes_cli/cron.py
@@ -4,7 +4,7 @@ import contextlib
import json
import re
import sys
-from datetime import timezone
+from datetime import timezone, UTC
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional
@@ -119,7 +119,7 @@ def _next_run_overdue_seconds(next_run_at: Any) -> Optional[float]:
if dt is None:
return None
# Same-tzinfo subtraction is wall-clock arithmetic in Python; compare instants.
- return (now().astimezone(timezone.utc) - dt.astimezone(timezone.utc)).total_seconds()
+ return (now().astimezone(UTC) - dt.astimezone(UTC)).total_seconds()
def _next_run_row(job: dict[str, Any]) -> tuple[str, str]:
@@ -625,7 +625,7 @@ def _print_active_jobs_summary(jobs) -> None:
# job its configured zone), so order by instant, never by ISO text; display the stored stamp.
# `_parse_aware` hands back one shared ZoneInfo, and Python compares same-tzinfo datetimes
# by wall clock (wrong across a DST fold) — normalise to UTC before ordering.
- next_runs = [(parsed.astimezone(timezone.utc), j["next_run_at"]) for j in jobs
+ next_runs = [(parsed.astimezone(UTC), j["next_run_at"]) for j in jobs
if (parsed := _parse_aware(j.get("next_run_at"))) is not None]
print(f" {len(jobs)} active job(s)")
if next_runs:
diff --git a/hermes_cli/curator.py b/hermes_cli/curator.py
index b02e8a4d5f7..96b99aae7a2 100644
--- a/hermes_cli/curator.py
+++ b/hermes_cli/curator.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import argparse
import sys
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Optional
@@ -15,7 +15,7 @@ def _parse_ts(ts) -> Optional[datetime]:
dt = datetime.fromisoformat(ts)
except (TypeError, ValueError):
return None
- return dt.replace(tzinfo=timezone.utc) if dt.tzinfo is None else dt
+ return dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt
def _fmt_ts(ts: Optional[str]) -> str:
@@ -24,7 +24,7 @@ def _fmt_ts(ts: Optional[str]) -> str:
dt = _parse_ts(ts)
if dt is None:
return str(ts)
- secs = int((datetime.now(timezone.utc) - dt).total_seconds())
+ secs = int((datetime.now(UTC) - dt).total_seconds())
for unit, div, limit in (("s", 1, 60), ("m", 60, 3600), ("h", 3600, 86400)):
if secs < limit:
return f"{secs // div}{unit} ago"
@@ -327,7 +327,7 @@ def _idle_days(record: dict) -> Optional[int]:
immortal; None only when both fields are missing or unparseable."""
ts = record.get("last_activity_at") or record.get("created_at")
dt = _parse_ts(str(ts)) if ts else None
- return None if dt is None else max(0, (datetime.now(timezone.utc) - dt).days)
+ return None if dt is None else max(0, (datetime.now(UTC) - dt).days)
def _cmd_prune(args) -> int:
diff --git a/hermes_cli/dashboard_auth/audit.py b/hermes_cli/dashboard_auth/audit.py
index 21cbd0de3c1..37d8553e883 100644
--- a/hermes_cli/dashboard_auth/audit.py
+++ b/hermes_cli/dashboard_auth/audit.py
@@ -99,7 +99,7 @@ def audit_log(event: AuditEvent, **fields: Any) -> None:
but never raise — auth must not fail because the audit logger broke."""
try:
entry = {
- "ts": _dt.datetime.now(_dt.timezone.utc).isoformat(),
+ "ts": _dt.datetime.now(_dt.UTC).isoformat(),
"event": event.value,
**{k: _bounded_value(v) for k, v in fields.items() if k not in _REDACTED_FIELDS}}
line = json.dumps(entry, separators=(",", ":")) + "\n"
diff --git a/hermes_cli/debug.py b/hermes_cli/debug.py
index fa6e9a4c68c..a10952d22b3 100644
--- a/hermes_cli/debug.py
+++ b/hermes_cli/debug.py
@@ -422,7 +422,7 @@ def build_nous_bundle(bundle: dict[str, str], redact: bool = True) -> bytes:
"""Gzip a :func:`collect_share_bundle` mapping into the Nous envelope (shape parsed by the
discord-support viewer — keep it stable)."""
envelope = {"format": _NOUS_BUNDLE_FORMAT, "redacted": bool(redact),
- "created": datetime.datetime.now(datetime.timezone.utc).isoformat(),
+ "created": datetime.datetime.now(datetime.UTC).isoformat(),
"files": bundle}
return gzip.compress(json.dumps(envelope).encode("utf-8"))
diff --git a/hermes_cli/dump.py b/hermes_cli/dump.py
index a064af81497..d0ea7f10c23 100644
--- a/hermes_cli/dump.py
+++ b/hermes_cli/dump.py
@@ -11,6 +11,7 @@ from hermes_cli.config import get_hermes_home, get_env_path, get_project_root, l
from hermes_cli.env_loader import load_hermes_dotenv
from hermes_constants import display_hermes_home
from agent.skill_utils import is_excluded_skill_path
+from datetime import UTC
def _dotenv_key_names() -> set[str]:
@@ -87,7 +88,7 @@ def _get_git_commit_date(project_root: Path) -> str:
from hermes_cli.version_info import get_version_info # deferred: keeps dump cheap on non-dump paths
commit_date = get_version_info().commit_date
- return datetime.fromtimestamp(commit_date, tz=timezone.utc).strftime("%Y-%m-%d") if commit_date else ""
+ return datetime.fromtimestamp(commit_date, tz=UTC).strftime("%Y-%m-%d") if commit_date else ""
except Exception:
return ""
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 5267c950401..48db06e61fc 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -4015,6 +4015,7 @@ from hermes_cli.gateway_launchd import (
wait_for_launchd_gateway_supervision,
launchd_status,
)
+from datetime import UTC
# Cached launchd domain — probe once per process invocation.
@@ -4540,7 +4541,7 @@ def _make_exit_diag():
log_dir = _ghh() / "logs"
log_dir.mkdir(parents=True, exist_ok=True)
line = {
- "ts": _dt.now(_tz.utc).isoformat(), "tag": tag, "pid": os.getpid(),
+ "ts": _dt.now(UTC).isoformat(), "tag": tag, "pid": os.getpid(),
"python": sys.version.split()[0], "platform": sys.platform, **extra,
}
with open(log_dir / "gateway-exit-diag.log", "a", encoding="utf-8") as f:
diff --git a/hermes_cli/gateway_launchd.py b/hermes_cli/gateway_launchd.py
index 8ffc3d4929f..0ec7ecd9a27 100644
--- a/hermes_cli/gateway_launchd.py
+++ b/hermes_cli/gateway_launchd.py
@@ -15,6 +15,7 @@ import subprocess
import sys
import time
from xml.sax.saxutils import escape
+from datetime import UTC
from hermes_cli import gateway_service_owner
@@ -192,7 +193,7 @@ def _write_launchd_unsupported_marker() -> None:
"""Persist that launchd cannot supervise the gateway on this host."""
from datetime import datetime, timezone
payload = {
- "written_at": datetime.now(timezone.utc).isoformat(),
+ "written_at": datetime.now(UTC).isoformat(),
"reason": "launchd domain unsupported (exit 5/125)",
}
with contextlib.suppress(OSError):
diff --git a/hermes_cli/gateway_windows.py b/hermes_cli/gateway_windows.py
index 2e2ad5107ec..7c6f6bfd041 100644
--- a/hermes_cli/gateway_windows.py
+++ b/hermes_cli/gateway_windows.py
@@ -19,7 +19,7 @@ import subprocess
import sys
import time
import uuid
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from xml.etree import ElementTree
from xml.sax.saxutils import escape
@@ -1085,7 +1085,7 @@ def _write_start_attestation(pids: list[int], via: str, home: Path | None = None
from hermes_cli.process_identity import _process_create_time
payload = {
- "pids": [int(p) for p in pids], "via": via, "ts": datetime.now(timezone.utc).isoformat(),
+ "pids": [int(p) for p in pids], "via": via, "ts": datetime.now(UTC).isoformat(),
"generation": uuid.uuid4().hex,
}
# Bind each PID to its incarnation (#110020 review): the ledger sentinel is matched by PID
@@ -1123,7 +1123,7 @@ def _attestation_within_horizon(data: object) -> bool:
if ts is None:
return False
if ts.tzinfo is None:
- ts = ts.replace(tzinfo=timezone.utc)
+ ts = ts.replace(tzinfo=UTC)
age = time.time() - ts.timestamp()
return -_ATTESTATION_CLOCK_SLACK_S <= age <= START_ATTESTATION_MAX_AGE_S
except Exception:
@@ -1571,7 +1571,7 @@ def _probe_state_file(state_path: Path) -> None:
if updated_at:
try:
updated_dt = datetime.fromisoformat(updated_at)
- age_seconds = int((datetime.now(timezone.utc) - updated_dt).total_seconds())
+ age_seconds = int((datetime.now(UTC) - updated_dt).total_seconds())
age_str = f" (updated {age_seconds}s ago)"
except Exception:
pass
diff --git a/hermes_cli/goals.py b/hermes_cli/goals.py
index d7d2aafe65a..11ee00ff8aa 100644
--- a/hermes_cli/goals.py
+++ b/hermes_cli/goals.py
@@ -17,7 +17,7 @@ import subprocess
import threading
import time
from dataclasses import dataclass, field, asdict
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
@@ -928,7 +928,7 @@ def judge_goal(
response=_truncate(last_response, _JUDGE_RESPONSE_SNIPPET_CHARS),
background_block=_render_background_block(background_processes)
+ (JUDGE_DELEGATIONS_BLOCK_TEMPLATE.format(count=active_delegations) if active_delegations > 0 else ""),
- current_time=safe_strftime(datetime.now(tz=timezone.utc).astimezone(), "%Y-%m-%d %H:%M:%S %Z"),
+ current_time=safe_strftime(datetime.now(tz=UTC).astimezone(), "%Y-%m-%d %H:%M:%S %Z"),
)
if contract is not None and not contract.is_empty():
contract_block = contract.render_block()
diff --git a/hermes_cli/inventory.py b/hermes_cli/inventory.py
index 2175b781e8b..e4a6011f0b7 100644
--- a/hermes_cli/inventory.py
+++ b/hermes_cli/inventory.py
@@ -7,6 +7,7 @@ from contextvars import copy_context
from dataclasses import dataclass, replace
from threading import Lock, Thread, current_thread
from typing import Any, Optional
+from datetime import UTC
_pricing_prewarm_lock = Lock()
_pricing_prewarm_threads: dict[tuple[str, tuple[tuple[str, str], ...]], Thread] = {}
@@ -265,7 +266,7 @@ def _apply_limits(rows: list[dict]) -> None:
from hermes_cli.auth import read_credential_pool
def iso(epoch: float) -> str:
- return datetime.fromtimestamp(epoch, timezone.utc).isoformat()
+ return datetime.fromtimestamp(epoch, UTC).isoformat()
pooled = {slug for slug, entries in read_credential_pool().items() if entries}
for row in rows:
@@ -361,7 +362,7 @@ _EXHAUSTED_WINDOW_PERCENT = 100.0
def _iso_from_epoch(epoch: float) -> str:
from datetime import datetime, timezone
- return datetime.fromtimestamp(float(epoch), timezone.utc).isoformat()
+ return datetime.fromtimestamp(float(epoch), UTC).isoformat()
def _pool_usage_accounts(slug: str, wire_windows, account_resets_at,
diff --git a/hermes_cli/nous_account.py b/hermes_cli/nous_account.py
index f08c1116d39..921a4a49d21 100644
--- a/hermes_cli/nous_account.py
+++ b/hermes_cli/nous_account.py
@@ -8,7 +8,7 @@ import threading
import time
import urllib.request
from dataclasses import dataclass, field, fields
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Literal, Optional
@@ -518,7 +518,7 @@ def _info_from_valid_jwt(
inference_base_url=_coerce_str(state.get("inference_base_url")),
inference_credential_present=True,
credential_source=_coerce_str(state.get("credential_source")) or "auth_store",
- expires_at=datetime.fromtimestamp(exp, tz=timezone.utc),
+ expires_at=datetime.fromtimestamp(exp, tz=UTC),
paid_service_access=paid_access, paid_service_access_info=access_info,
tool_access=_tool_access_from_value(claims.get("tool_access")),
raw_claims=dict(claims),
diff --git a/hermes_cli/observability/shared_metrics.py b/hermes_cli/observability/shared_metrics.py
index 62e092912ab..86084f0715d 100644
--- a/hermes_cli/observability/shared_metrics.py
+++ b/hermes_cli/observability/shared_metrics.py
@@ -10,7 +10,7 @@ import threading
import uuid
from collections.abc import Callable, Iterator
from contextlib import contextmanager
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
from typing import Any
@@ -156,11 +156,11 @@ logger = logging.getLogger(__name__)
def _utc_now() -> datetime:
- return datetime.now(timezone.utc)
+ return datetime.now(UTC)
def _isoformat(value: datetime) -> str:
- return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
+ return value.astimezone(UTC).isoformat().replace("+00:00", "Z")
def _compact_json(value: Any) -> str:
@@ -555,7 +555,7 @@ class SharedMetricsStore:
parsed = datetime.fromisoformat(str(value))
except (TypeError, ValueError):
return None
- return None if parsed.tzinfo is None else parsed.astimezone(timezone.utc)
+ return None if parsed.tzinfo is None else parsed.astimezone(UTC)
def _create_pending_packages_if_due(self) -> None:
now = _utc_now()
@@ -600,7 +600,7 @@ class SharedMetricsStore:
""",
(period_value, *resource_values),
).fetchall()
- period_start = datetime.fromisoformat(str(period_value)).replace(tzinfo=timezone.utc)
+ period_start = datetime.fromisoformat(str(period_value)).replace(tzinfo=UTC)
if not client_resource_is_valid(resource):
raise ValueError("Unsupported shared-metrics client resource")
payload = {
diff --git a/hermes_cli/observability/shared_metrics_desktop.py b/hermes_cli/observability/shared_metrics_desktop.py
index 6c0683f5705..c20852d2955 100644
--- a/hermes_cli/observability/shared_metrics_desktop.py
+++ b/hermes_cli/observability/shared_metrics_desktop.py
@@ -19,7 +19,7 @@ import platform
import re
import shutil
import threading
-from datetime import date, datetime, timedelta, timezone
+from datetime import date, datetime, timedelta, timezone, UTC
from typing import Any
from . import shared_metrics_contract as contract
@@ -44,7 +44,7 @@ _daily: dict[tuple[str, str, str], int] = {}
def _utc_day() -> str:
- return datetime.now(timezone.utc).date().isoformat()
+ return datetime.now(UTC).date().isoformat()
def _home() -> str:
diff --git a/hermes_cli/observability/shared_metrics_engagement.py b/hermes_cli/observability/shared_metrics_engagement.py
index 25671fa2b29..d9912f2a650 100644
--- a/hermes_cli/observability/shared_metrics_engagement.py
+++ b/hermes_cli/observability/shared_metrics_engagement.py
@@ -27,7 +27,7 @@ import hashlib
import threading
import time
from dataclasses import dataclass
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Callable
@@ -168,7 +168,7 @@ def _root_store(home: Path) -> Any:
# ---- the rollup (pure) ---------------------------------------------------------------------------
def _utc_day(now_ms: int) -> str:
- return datetime.fromtimestamp(now_ms / 1000, tz=timezone.utc).date().isoformat()
+ return datetime.fromtimestamp(now_ms / 1000, tz=UTC).date().isoformat()
def _fresh(day: str, resource: dict[str, str], owner: bool) -> dict[str, Any]:
diff --git a/hermes_cli/observability/shared_metrics_gateway.py b/hermes_cli/observability/shared_metrics_gateway.py
index 2f1bd40ec94..479dd5f2cee 100644
--- a/hermes_cli/observability/shared_metrics_gateway.py
+++ b/hermes_cli/observability/shared_metrics_gateway.py
@@ -19,7 +19,7 @@ import threading
import time
from collections import OrderedDict
from concurrent.futures import Future, ThreadPoolExecutor
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Callable
logger = logging.getLogger(__name__)
@@ -198,7 +198,7 @@ def _record_connect(platform: Any, event: str, *, exc: BaseException | None, fat
# Keyed by the real adapter (two custom adapters both emit "plugin"); projected only at emission.
key = (str(get_hermes_home()), str(getattr(platform, "value", platform)))
- day = datetime.now(timezone.utc).date().isoformat()
+ day = datetime.now(UTC).date().isoformat()
if event != "connect_failed" or terminal:
counted = _failing_connects.pop(key, None) == day
elif not enabled(): # nothing is recorded, so nothing is latched: opting in mid-outage counts it
diff --git a/hermes_cli/observability/shared_metrics_install_run.py b/hermes_cli/observability/shared_metrics_install_run.py
index 012c218603e..05fb79839fb 100644
--- a/hermes_cli/observability/shared_metrics_install_run.py
+++ b/hermes_cli/observability/shared_metrics_install_run.py
@@ -23,7 +23,7 @@ import re
import shutil
import sqlite3
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any
@@ -100,7 +100,7 @@ def _today_start() -> str:
"""Today's package ``period_start``, in the store's stamp format (``shared_metrics._isoformat``)."""
from .shared_metrics import _isoformat, _utc_now
- return _isoformat(datetime.combine(_utc_now().date(), datetime.min.time(), tzinfo=timezone.utc))
+ return _isoformat(datetime.combine(_utc_now().date(), datetime.min.time(), tzinfo=UTC))
def consented_day(home: Path) -> bool:
diff --git a/hermes_cli/observability/shared_metrics_sender.py b/hermes_cli/observability/shared_metrics_sender.py
index adfc354374e..7c09448137e 100644
--- a/hermes_cli/observability/shared_metrics_sender.py
+++ b/hermes_cli/observability/shared_metrics_sender.py
@@ -18,7 +18,7 @@ import urllib.request
import uuid
from contextlib import contextmanager
from dataclasses import dataclass
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from agent.retry_utils import parse_retry_after_seconds
from hermes_cli.sqlite_util import write_txn
@@ -70,7 +70,7 @@ MAX_OBS_ADVANCE_SECONDS = 30 * 24 * 3600
def _parse_stamp(value: str) -> datetime:
"""Parse a stamp this module itself wrote (Z-suffixed ISO-8601, UTC)."""
- return datetime.fromisoformat(value).astimezone(timezone.utc)
+ return datetime.fromisoformat(value).astimezone(UTC)
@dataclass
@@ -403,7 +403,7 @@ class SharedMetricsSender:
package_id,
token=token,
send_state="pending",
- next_attempt_at=_isoformat(datetime.fromtimestamp(retry_at, tz=timezone.utc)),
+ next_attempt_at=_isoformat(datetime.fromtimestamp(retry_at, tz=UTC)),
last_error=reason[:500],
)
diff --git a/hermes_cli/plugin_capabilities.py b/hermes_cli/plugin_capabilities.py
index 9fe467fe199..9ff779820e7 100644
--- a/hermes_cli/plugin_capabilities.py
+++ b/hermes_cli/plugin_capabilities.py
@@ -9,7 +9,7 @@ from __future__ import annotations
import hashlib
import logging
from dataclasses import dataclass
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple
logger = logging.getLogger(__name__)
@@ -170,7 +170,7 @@ def record_consent(plugin_id: str, granted: Iterable[str], declared: Iterable[st
entry[GRANTED_KEY] = sorted(_known(c for c in merged if isinstance(c, str)))
entry[CONSENT_KEY] = {
"hash": capability_set_hash(_known(declared)),
- "granted_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
+ "granted_at": datetime.now(UTC).isoformat(timespec="seconds"),
}
# Bridge: mirror each grant into its legacy gate (enforcement sites still read allow_*).
for cap in entry[GRANTED_KEY]:
diff --git a/hermes_cli/plugin_catalog.py b/hermes_cli/plugin_catalog.py
index 63a9466c1a7..29d1e5ffc41 100644
--- a/hermes_cli/plugin_catalog.py
+++ b/hermes_cli/plugin_catalog.py
@@ -24,6 +24,7 @@ from pathlib import Path
from typing import Any, Dict, List, Optional
import hermes_yaml as yaml
+from datetime import UTC
logger = logging.getLogger(__name__)
@@ -443,7 +444,7 @@ def _live_generated_time(data: dict[str, Any]) -> Optional[float]:
try:
from datetime import datetime, timezone
parsed = datetime.fromisoformat(raw)
- return (parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)).timestamp()
+ return (parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)).timestamp()
except ValueError:
return None
diff --git a/hermes_cli/plugins_cmd_catalog.py b/hermes_cli/plugins_cmd_catalog.py
index 189d070680f..b20678ccc08 100644
--- a/hermes_cli/plugins_cmd_catalog.py
+++ b/hermes_cli/plugins_cmd_catalog.py
@@ -71,7 +71,7 @@ def write_catalog_sidecar_record(target: Path, catalog: dict, sha: str) -> None:
sidecar = {
"catalog_name": catalog["name"], "repo": catalog["repo"], "sha": sha,
"tier": catalog.get("tier") or "community",
- "installed_at": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
+ "installed_at": datetime.datetime.now(datetime.UTC).isoformat(timespec="seconds")
.replace("+00:00", "Z"),
}
try:
@@ -834,7 +834,7 @@ def installed_catalog_state(installed: dict[str, dict[str, Any]]) -> dict[str, A
return {
"entries": entries,
"removed": [{"name": r.name, "repo": r.repo, "reason": r.reason, "date": r.date} for r in resolved_removed_entries()],
- "generated_at": datetime.datetime.now(datetime.timezone.utc).isoformat().replace("+00:00", "Z"),
+ "generated_at": datetime.datetime.now(datetime.UTC).isoformat().replace("+00:00", "Z"),
}
diff --git a/hermes_cli/post_update.py b/hermes_cli/post_update.py
index ac621e206d3..4bdfcc80064 100644
--- a/hermes_cli/post_update.py
+++ b/hermes_cli/post_update.py
@@ -10,7 +10,7 @@ from __future__ import annotations
import logging
import os
import shutil
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Iterable
@@ -37,7 +37,7 @@ def _backup_path(path: Path, stamp: str) -> Path:
def _backup_existing(paths: Iterable[Path]) -> dict:
- stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
+ stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
backups: dict = {}
for path in paths:
if not path.is_file():
@@ -238,7 +238,7 @@ def step_adopt_blessed_checkout(project_root: Path | None = None) -> dict:
"schemaVersion": 2,
"updateMechanism": "self",
"source": "adoption",
- "adoptedAt": datetime.now(timezone.utc).isoformat(),
+ "adoptedAt": datetime.now(UTC).isoformat(),
}
try:
fd, tmp_name = tempfile.mkstemp(
diff --git a/hermes_cli/profile_distribution.py b/hermes_cli/profile_distribution.py
index f685a21c3a6..181a4d63336 100644
--- a/hermes_cli/profile_distribution.py
+++ b/hermes_cli/profile_distribution.py
@@ -14,7 +14,7 @@ import shutil
import subprocess
import tempfile
from dataclasses import dataclass, field
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
@@ -332,7 +332,7 @@ def plan_install(source: str, workdir: Path, override_name: Optional[str] = None
manifest.name = canon
manifest.source = provenance
# Stamped once here so both fresh install and update propagate a fresh timestamp.
- manifest.installed_at = datetime.now(timezone.utc).isoformat(timespec="seconds")
+ manifest.installed_at = datetime.now(UTC).isoformat(timespec="seconds")
target_dir = get_profile_dir(canon)
existing = target_dir.is_dir()
return InstallPlan(
diff --git a/hermes_cli/session_export.py b/hermes_cli/session_export.py
index ef82a493fdd..c9548f2ab6e 100644
--- a/hermes_cli/session_export.py
+++ b/hermes_cli/session_export.py
@@ -7,7 +7,7 @@ only loads sessions and writes bytes.
from __future__ import annotations
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from html import escape as html_escape
import json
from typing import Any, Dict, Iterable, Iterator, List, Literal, Optional, Tuple
@@ -163,11 +163,11 @@ def _format_timestamp(value: Any, session_id: Optional[str] = None) -> Optional[
if value is None:
return None
if isinstance(value, datetime):
- dt = (value if value.tzinfo else value.replace(tzinfo=timezone.utc)).astimezone(timezone.utc)
+ dt = (value if value.tzinfo else value.replace(tzinfo=UTC)).astimezone(UTC)
elif (ts := coerce_epoch(value, session_id=session_id)) is None:
return str(value) # corrupt cell: odd-looking date, not an aborted export
else:
- dt = datetime.fromtimestamp(ts, tz=timezone.utc)
+ dt = datetime.fromtimestamp(ts, tz=UTC)
return dt.isoformat(timespec="seconds").replace("+00:00", "Z")
diff --git a/hermes_cli/session_export_md.py b/hermes_cli/session_export_md.py
index 87478e2d861..faefcc25f1a 100644
--- a/hermes_cli/session_export_md.py
+++ b/hermes_cli/session_export_md.py
@@ -10,7 +10,7 @@ import hashlib
import json
import re
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any
@@ -27,7 +27,7 @@ def _iso_timestamp(value: Any) -> str:
return ""
if (ts := coerce_epoch(value)) is None:
return str(value) # corrupt cell: odd-looking date, not an aborted export
- return datetime.fromtimestamp(ts, tz=timezone.utc).isoformat().replace("+00:00", "Z")
+ return datetime.fromtimestamp(ts, tz=UTC).isoformat().replace("+00:00", "Z")
def _frontmatter_line(key: str, value: Any) -> str:
diff --git a/hermes_cli/session_filters.py b/hermes_cli/session_filters.py
index e09a7b696f4..cdc0f860b3b 100644
--- a/hermes_cli/session_filters.py
+++ b/hermes_cli/session_filters.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import re
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Dict, Optional
from hermes_cli.timefmt import coerce_epoch
@@ -49,7 +49,7 @@ def parse_point_in_time(value: str, flag: str) -> float:
f"'30m', '2d', '1w', a bare number of days, or an ISO timestamp "
f"like '2026-07-05' or '2026-07-05 14:30'."
) from None
- return dt.timestamp() if dt.tzinfo is None else dt.astimezone(timezone.utc).timestamp()
+ return dt.timestamp() if dt.tzinfo is None else dt.astimezone(UTC).timestamp()
def format_epoch(ts: Optional[float]) -> str:
diff --git a/hermes_cli/setup_profile.py b/hermes_cli/setup_profile.py
index 3622c90f638..fe1c1d22824 100644
--- a/hermes_cli/setup_profile.py
+++ b/hermes_cli/setup_profile.py
@@ -5,7 +5,7 @@ import logging
import os
import random
import shutil
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Callable, NamedTuple, Optional
@@ -201,7 +201,7 @@ def mark_intro_seen() -> dict:
def mark_completed() -> dict:
- completed_at = datetime.now(timezone.utc).isoformat()
+ completed_at = datetime.now(UTC).isoformat()
return _change_state(lambda state: {**state, "intro": "seen", "completed_at": completed_at})
diff --git a/hermes_cli/skills_hub.py b/hermes_cli/skills_hub.py
index 518b839403d..99f8d50428c 100644
--- a/hermes_cli/skills_hub.py
+++ b/hermes_cli/skills_hub.py
@@ -6,7 +6,7 @@ import logging
import re
import shutil
import sys
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Dict, List, Optional
@@ -1452,7 +1452,7 @@ def do_snapshot_export(output_path: str, console: Optional[Console] = None) -> N
tap_list = TapsManager().list_taps()
snapshot = {
"hermes_version": "0.1.0",
- "exported_at": datetime.now(timezone.utc).isoformat(),
+ "exported_at": datetime.now(UTC).isoformat(),
"skills": [
{"name": entry["name"], "source": entry.get("source", ""),
"identifier": entry.get("identifier", ""),
diff --git a/hermes_cli/source_stamp.py b/hermes_cli/source_stamp.py
index 7416bf7bda1..9bbb6dcb519 100644
--- a/hermes_cli/source_stamp.py
+++ b/hermes_cli/source_stamp.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from contextlib import suppress
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
import json
import os
from pathlib import Path
@@ -34,7 +34,7 @@ def write_source_stamp(root: Path, *, adopted: bool = False) -> dict | None:
"commit": info.commit,
"commitDate": info.commit_date,
"branch": info.branch,
- "builtAt": datetime.now(timezone.utc).isoformat(),
+ "builtAt": datetime.now(UTC).isoformat(),
"dirty": info.dirty,
"source": "git",
"distribution": None,
@@ -98,7 +98,7 @@ def refresh_bootstrap_receipt(root: Path, stamp: dict) -> None:
"pinnedCommit": stamp["commit"],
# A detached checkout keeps the branch it was installed from.
"pinnedBranch": stamp["branch"] or previous.get("pinnedBranch"),
- "completedAt": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z",
+ "completedAt": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z",
}
fd, tmp_name = tempfile.mkstemp(dir=root, prefix=".hermes-bootstrap-complete.", suffix=".tmp")
try:
diff --git a/hermes_cli/status_auth.py b/hermes_cli/status_auth.py
index cc4dff680a3..ce18e8ac5a9 100644
--- a/hermes_cli/status_auth.py
+++ b/hermes_cli/status_auth.py
@@ -2,7 +2,7 @@
Origin helpers (``_row``, ``_first_env_value``, ...) are resolved through the ``hermes_cli.status``
module object so tests that monkeypatch that module keep working."""
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from hermes_cli.auth import AuthError
from hermes_cli.nous_account import (
@@ -23,12 +23,12 @@ def _format_iso_timestamp(value) -> str:
except Exception:
return value
if parsed.tzinfo is None:
- parsed = parsed.replace(tzinfo=timezone.utc)
+ parsed = parsed.replace(tzinfo=UTC)
return safe_strftime(parsed.astimezone(), "%Y-%m-%d %H:%M:%S %Z")
def _qwen_expiry(expires_at_ms) -> str:
- return datetime.fromtimestamp(int(expires_at_ms) / 1000, tz=timezone.utc).isoformat()
+ return datetime.fromtimestamp(int(expires_at_ms) / 1000, tz=UTC).isoformat()
def _oauth_block(name: str, status: dict, hint: str, rows) -> None:
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 7413d75b324..c43e7eb590f 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -117,6 +117,7 @@ from hermes_cli.update_cmd_maint import (
_sweep_bytecode_after_update,
_update_complete_message, _verify_and_restore_one_state_db,
_verify_and_restore_state_dbs_post_update)
+from datetime import UTC
logger = logging.getLogger(__name__)
@@ -887,7 +888,7 @@ def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha, *, target_r
kind = "diverged" if has_common_ancestor else "orphan"
rescue_ref = (
f"refs/hermes-update-backups/{kind}-{branch}-"
- f"{_dt.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}-{pre_pull_sha[:12]}")
+ f"{_dt.now(UTC).strftime('%Y%m%d-%H%M%S')}-{pre_pull_sha[:12]}")
head = (
f" ⚠ Local history has diverged from origin/{branch} — "
if has_common_ancestor else
diff --git a/hermes_cli/update_cmd_git.py b/hermes_cli/update_cmd_git.py
index 48193957efe..3a8786f2e57 100644
--- a/hermes_cli/update_cmd_git.py
+++ b/hermes_cli/update_cmd_git.py
@@ -9,7 +9,7 @@ import logging
from contextlib import nullcontext, suppress
import subprocess
import sys
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
from typing import Optional
@@ -97,11 +97,11 @@ def _prune_orphan_rescue_refs(
refs = [line.strip() for line in list_result.stdout.splitlines() if line.strip()]
stale |= set(refs[:-keep] if keep > 0 else refs)
if max_age_days > 0:
- cutoff = datetime.now(timezone.utc) - timedelta(days=max_age_days)
+ cutoff = datetime.now(UTC) - timedelta(days=max_age_days)
for ref in refs:
with suppress(ValueError):
stamp = datetime.strptime(ref[len(prefix):][:15], "%Y%m%d-%H%M%S")
- if stamp.replace(tzinfo=timezone.utc) < cutoff:
+ if stamp.replace(tzinfo=UTC) < cutoff:
stale.add(ref)
for ref in sorted(stale):
_git_run(git_cmd, ["update-ref", "-d", ref], cwd)
@@ -128,7 +128,7 @@ def _park_detached_head(git_cmd, cwd, branch) -> None:
holders = [r for r in (contains.stdout or "").split() if r != "refs/stash"]
if contains.returncode == 0 and holders:
return # already reachable from a branch, tag, remote or backup ref
- stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
+ stamp = datetime.now(UTC).strftime("%Y%m%d-%H%M%S")
rescue_ref = f"refs/hermes-update-backups/detached-{branch}-{stamp}-{sha[:12]}"
if _git_run(git_cmd, ["update-ref", rescue_ref, sha], cwd).returncode != 0:
print(f"✗ HEAD is detached at {sha[:12]}, which no branch or tag contains, and backing it up "
diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.py
index e50d360bd4a..5861770c001 100644
--- a/hermes_cli/update_cmd_maint.py
+++ b/hermes_cli/update_cmd_maint.py
@@ -16,6 +16,7 @@ from pathlib import Path
from typing import Optional
from hermes_cli.update_cmd_common import _best_effort
+from datetime import UTC
# Log-record parity with the origin module.
logger = logging.getLogger("hermes_cli.update_cmd")
@@ -240,8 +241,8 @@ def _format_time_ago(iso_ts: str) -> str:
from datetime import datetime, timezone
ts = datetime.fromisoformat(iso_ts)
if ts.tzinfo is None:
- ts = ts.replace(tzinfo=timezone.utc)
- secs = int((datetime.now(timezone.utc) - ts).total_seconds())
+ ts = ts.replace(tzinfo=UTC)
+ secs = int((datetime.now(UTC) - ts).total_seconds())
if secs < 60:
return "just now"
if secs < 3600:
diff --git a/hermes_cli/update_cmd_stash.py b/hermes_cli/update_cmd_stash.py
index 4f5fb6648ed..b73e140a542 100644
--- a/hermes_cli/update_cmd_stash.py
+++ b/hermes_cli/update_cmd_stash.py
@@ -7,7 +7,7 @@ Origin helpers are imported lazily per function (no cycle; test patches on the o
import logging
import re
import subprocess
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
from typing import Optional
@@ -111,7 +111,7 @@ def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path, *, checkout_mo
if add.returncode != 0:
_print_nonempty(add.stderr)
- stash_name = datetime.now(timezone.utc).strftime(f"{_AUTOSTASH_NAME_PREFIX}%Y%m%d-%H%M%S")
+ stash_name = datetime.now(UTC).strftime(f"{_AUTOSTASH_NAME_PREFIX}%Y%m%d-%H%M%S")
print("→ Local changes detected — stashing before update...")
prev_stash = _git_run(git_cmd, ["rev-parse", "--verify", "refs/stash"], cwd).stdout.strip()
with (checkout_move or _no_move)(revert=True): # push and reset put every tracked change back to HEAD
@@ -202,7 +202,7 @@ def _warn_orphaned_update_autostashes(git_cmd: list[str], cwd: Path) -> int:
stash_list = _git_run(git_cmd, ["stash", "list", "--format=%gd %s"], cwd)
if stash_list.returncode != 0:
return 0
- cutoff = datetime.now(timezone.utc) - timedelta(days=_AUTOSTASH_WARN_AGE_DAYS)
+ cutoff = datetime.now(UTC) - timedelta(days=_AUTOSTASH_WARN_AGE_DAYS)
stale: list[tuple[str, str]] = []
for line in stash_list.stdout.splitlines():
selector, _, subject = line.strip().partition(" ")
@@ -211,7 +211,7 @@ def _warn_orphaned_update_autostashes(git_cmd: list[str], cwd: Path) -> int:
continue
stamp = subject[pos + len(_AUTOSTASH_NAME_PREFIX):][:15] # "YYYYMMDD-HHMMSS"
try:
- stash_time = datetime.strptime(stamp, "%Y%m%d-%H%M%S").replace(tzinfo=timezone.utc)
+ stash_time = datetime.strptime(stamp, "%Y%m%d-%H%M%S").replace(tzinfo=UTC)
except ValueError:
continue # age unknown — leave it alone rather than guess
if stash_time < cutoff:
diff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.py
index 25596632628..3ca4a4694d7 100644
--- a/hermes_cli/update_cmd_windows.py
+++ b/hermes_cli/update_cmd_windows.py
@@ -12,7 +12,7 @@ import shlex
import subprocess
import sys
import time as _time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from hermes_cli.update_cmd_common import _best_effort
@@ -62,7 +62,7 @@ def _write_update_planned_stop_marker(profile_path: Path, pid: int) -> bool:
atomic_json_write(
_planned_stop_marker_path(profile_path),
{"target_pid": pid, "target_start_time": _get_process_start_time(pid), "stopper_pid": os.getpid(),
- "written_at": datetime.now(timezone.utc).isoformat()},
+ "written_at": datetime.now(UTC).isoformat()},
indent=None, separators=(",", ":"),
)
return True
diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.py
index c0a652a5765..68ea05a9437 100644
--- a/hermes_cli/update_receipt.py
+++ b/hermes_cli/update_receipt.py
@@ -40,7 +40,7 @@ import sys
import time
import uuid
from contextlib import contextmanager, suppress
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Optional
@@ -108,7 +108,7 @@ def current_correlation_id() -> Optional[str]:
def _utc_now_iso() -> str:
- return datetime.now(timezone.utc).isoformat()
+ return datetime.now(UTC).isoformat()
def _code_identity(refresh: bool = False) -> dict[str, Any]:
diff --git a/hermes_cli/web_routers/messaging.py b/hermes_cli/web_routers/messaging.py
index c25151b2298..35f1736f625 100644
--- a/hermes_cli/web_routers/messaging.py
+++ b/hermes_cli/web_routers/messaging.py
@@ -15,7 +15,7 @@ import subprocess
import threading
import time
import urllib.parse
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Optional
@@ -588,7 +588,7 @@ async def start_whatsapp_onboarding(body: WhatsAppOnboardingStart):
expires_at_ts = time.time() + _WHATSAPP_ONBOARDING_TTL_SECONDS
fields = dict(
proc=None, mode=mode, allowed_users=allowed_users, session_path=str(session_path),
- expires_at=datetime.fromtimestamp(expires_at_ts, timezone.utc).isoformat().replace("+00:00", "Z"),
+ expires_at=datetime.fromtimestamp(expires_at_ts, UTC).isoformat().replace("+00:00", "Z"),
expires_at_ts=expires_at_ts, profile=body.profile,
)
already_linked = (session_path / "creds.json").exists()
@@ -672,7 +672,7 @@ def _parse_expiry_ts(value: str) -> float:
try:
parsed = datetime.fromisoformat(value)
if parsed.tzinfo is None:
- parsed = parsed.replace(tzinfo=timezone.utc)
+ parsed = parsed.replace(tzinfo=UTC)
return parsed.timestamp()
except Exception:
return time.time() + 600
diff --git a/hermes_cli/web_routers/oauth.py b/hermes_cli/web_routers/oauth.py
index c4184e8f43a..9f30c543539 100644
--- a/hermes_cli/web_routers/oauth.py
+++ b/hermes_cli/web_routers/oauth.py
@@ -12,7 +12,7 @@ import secrets
import sys
import threading
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Callable, Dict, Optional
from fastapi import APIRouter, HTTPException, Request
@@ -367,7 +367,7 @@ def _status_card(
def _epoch_ms_to_iso(value: Any) -> Optional[str]:
"""Epoch ms (Qwen CLI ``expiry_date``) -> the aware ISO string the other cards send."""
- return datetime.fromtimestamp(value / 1000, tz=timezone.utc).isoformat() if value else None
+ return datetime.fromtimestamp(value / 1000, tz=UTC).isoformat() if value else None
# Hand-written status cards per provider id: (hauth getter name, raw -> card).
diff --git a/hermes_cli/web_routers/ops.py b/hermes_cli/web_routers/ops.py
index d4dc0424308..41c09ee09c5 100644
--- a/hermes_cli/web_routers/ops.py
+++ b/hermes_cli/web_routers/ops.py
@@ -13,7 +13,7 @@ import re
import secrets
import time
import zipfile
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Dict, List, Optional
@@ -651,7 +651,7 @@ async def run_import_upload(
except OSError as exc:
raise HTTPException(status_code=500, detail=f"Could not create import staging directory: {exc}")
- stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
+ stamp = datetime.now(UTC).strftime("%Y%m%d-%H%M%S")
target = staging_dir / f"dashboard-import-{stamp}-{secrets.token_hex(4)}-{_safe_backup_upload_name(file.filename)}"
total = await stream_upload_to_path(
file, target, too_large="Archive is too large",
diff --git a/hermes_cli/web_server_oauth.py b/hermes_cli/web_server_oauth.py
index 7c7aae60c77..f19e96f3a1c 100644
--- a/hermes_cli/web_server_oauth.py
+++ b/hermes_cli/web_server_oauth.py
@@ -8,7 +8,7 @@ import functools
import os
import threading
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Dict, Optional
# Same logger the code used before extraction (record parity).
@@ -324,7 +324,7 @@ def _nous_plain_poller(session_id: str, sess: dict[str, Any]) -> None:
if _cancelled():
return
# Same post-processing as _nous_device_code_login (validate/refresh JWT)
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
token_ttl = int(token_data.get("expires_in") or 0)
auth_state = {
"portal_base_url": portal_base_url,
@@ -336,7 +336,7 @@ def _nous_plain_poller(session_id: str, sess: dict[str, Any]) -> None:
"refresh_token": token_data.get("refresh_token"),
"obtained_at": now.isoformat(),
"expires_at": (
- datetime.fromtimestamp(now.timestamp() + token_ttl, tz=timezone.utc).isoformat()
+ datetime.fromtimestamp(now.timestamp() + token_ttl, tz=UTC).isoformat()
if token_ttl else None
),
"expires_in": token_ttl,
@@ -380,7 +380,7 @@ def _minimax_poller(session_id: str, sess: dict[str, Any]) -> None:
user_code=sess["user_code"], code_verifier=sess["code_verifier"],
expired_in=sess["expired_in_raw"], interval_ms=sess.get("interval_ms"),
)
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
expires_at_ts = _minimax_resolve_token_expiry_unix(int(token_data["expired_in"]), now=now)
auth_state = {
"provider": "minimax-oauth",
@@ -394,7 +394,7 @@ def _minimax_poller(session_id: str, sess: dict[str, Any]) -> None:
"refresh_token": token_data["refresh_token"],
"resource_url": token_data.get("resource_url"),
"obtained_at": now.isoformat(),
- "expires_at": datetime.fromtimestamp(expires_at_ts, tz=timezone.utc).isoformat(),
+ "expires_at": datetime.fromtimestamp(expires_at_ts, tz=UTC).isoformat(),
"expires_in": max(0, int(expires_at_ts - now.timestamp())),
}
with _profile_scope(sess.get("profile")):
@@ -438,7 +438,7 @@ def _xai_device_poller(session_id: str, sess: dict[str, Any]) -> None:
# set_active=False: persist without hijacking an existing active chat provider.
_save_xai_oauth_tokens(
tokens, discovery=discovery, auth_mode="oauth_device_code", set_active=False,
- last_refresh=datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
+ last_refresh=datetime.now(UTC).isoformat().replace("+00:00", "Z"),
)
# Mirror `hermes auth add xai-oauth`: first credential may become active; never overwrite.
mark_provider_active_if_unset("xai-oauth")
diff --git a/hermes_startup_watchdog.py b/hermes_startup_watchdog.py
index 622cc5c852a..f5ab0e9f052 100644
--- a/hermes_startup_watchdog.py
+++ b/hermes_startup_watchdog.py
@@ -34,7 +34,7 @@ import logging
import os
import threading
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Dict, Optional
@@ -287,7 +287,7 @@ class StartupWatchdogHandle:
)
_write_dump_record(
{
- "ts": datetime.now(timezone.utc).isoformat(),
+ "ts": datetime.now(UTC).isoformat(),
"tag": "startup_watchdog.fired",
"pid": os.getpid(),
"timeout_s": self.timeout_s,
diff --git a/hermes_state_portability.py b/hermes_state_portability.py
index 11071c13070..c2dbbd10da2 100644
--- a/hermes_state_portability.py
+++ b/hermes_state_portability.py
@@ -9,7 +9,7 @@ import json
import math
import time
from collections import Counter
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Dict, List, Optional
from agent.skill_commands import AUTO_LOAD_SCAFFOLD_SQL_LIKE, SKILL_SCAFFOLD_SQL_LIKE
@@ -109,7 +109,7 @@ def _export_timings(messages: list[dict[str, Any]], session_id: Optional[str] =
"from_role": prev.get("role"), "to_role": nxt.get("role"),
"gap_ms": max(0, round((nxt_ts - prev_ts) * 1000)),
} for (prev, prev_ts), (nxt, nxt_ts) in itertools.pairwise(timestamped)]
- iso = lambda ts: datetime.fromtimestamp(ts, tz=timezone.utc).isoformat()
+ iso = lambda ts: datetime.fromtimestamp(ts, tz=UTC).isoformat()
first_ts, last_ts = (timestamped[0][1], timestamped[-1][1]) if timestamped else (None, None)
return {
"source": "message_timestamps",
diff --git a/hermes_state_schema.py b/hermes_state_schema.py
index e2c5f65b79a..bf32e8ab7d9 100644
--- a/hermes_state_schema.py
+++ b/hermes_state_schema.py
@@ -990,7 +990,7 @@ class SessionSchemaMixin:
cursor.execute("INSERT INTO schema_version (version) VALUES (?)", (SCHEMA_VERSION,))
# Store provenance so fresh vs wiped stores are distinguishable.
# See #97568.
- now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat()
+ now_iso = datetime.datetime.now(datetime.UTC).isoformat()
cursor.executemany(
"INSERT OR IGNORE INTO state_meta (key, value) VALUES (?, ?)",
[("store_instance_id", str(uuid.uuid4())), ("store_created_at_utc", now_iso),
diff --git a/optional-skills/blockchain/hyperliquid/scripts/hyperliquid_client.py b/optional-skills/blockchain/hyperliquid/scripts/hyperliquid_client.py
index e8e4be4dbfc..8adaa291e23 100644
--- a/optional-skills/blockchain/hyperliquid/scripts/hyperliquid_client.py
+++ b/optional-skills/blockchain/hyperliquid/scripts/hyperliquid_client.py
@@ -171,7 +171,7 @@ def _format_timestamp_ms(value: Any) -> str:
ts_ms = int(value)
except (TypeError, ValueError):
return "-"
- return dt.datetime.fromtimestamp(ts_ms / 1000, dt.timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
+ return dt.datetime.fromtimestamp(ts_ms / 1000, dt.UTC).strftime("%Y-%m-%d %H:%M:%S UTC")
def _compact_number(value: Any, decimals: int = 2) -> str:
diff --git a/optional-skills/finance/polymarket/scripts/polymarket.py b/optional-skills/finance/polymarket/scripts/polymarket.py
index 9e9d587ba7f..e1efddd4104 100644
--- a/optional-skills/finance/polymarket/scripts/polymarket.py
+++ b/optional-skills/finance/polymarket/scripts/polymarket.py
@@ -17,6 +17,7 @@ import sys
import urllib.request
import urllib.parse
import urllib.error
+from datetime import UTC
GAMMA = "https://gamma-api.polymarket.com"
CLOB = "https://clob.polymarket.com"
@@ -205,7 +206,7 @@ def cmd_history(condition_id: str, interval: str = "all", fidelity: int = 50):
print(f"Price history ({len(history)} points, interval={interval}):\n")
from datetime import datetime, timezone
for pt in history:
- ts = datetime.fromtimestamp(pt["t"], tz=timezone.utc).strftime("%Y-%m-%d %H:%M")
+ ts = datetime.fromtimestamp(pt["t"], tz=UTC).strftime("%Y-%m-%d %H:%M")
price = _fmt_pct(pt["p"])
bar = "█" * int(float(pt["p"]) * 40)
print(f" {ts} {price:>7} {bar}")
diff --git a/optional-skills/finance/stocks/scripts/stocks_client.py b/optional-skills/finance/stocks/scripts/stocks_client.py
index c0bf97dce4a..3db9b9f5810 100755
--- a/optional-skills/finance/stocks/scripts/stocks_client.py
+++ b/optional-skills/finance/stocks/scripts/stocks_client.py
@@ -12,7 +12,7 @@ import time
import urllib.error
import urllib.parse
import urllib.request
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from http.cookiejar import CookieJar
# ---------------------------------------------------------------------------
@@ -93,7 +93,7 @@ def ts_to_date(ts) -> str | None:
if ts is None:
return None
try:
- return datetime.fromtimestamp(int(ts), tz=timezone.utc).strftime("%Y-%m-%d")
+ return datetime.fromtimestamp(int(ts), tz=UTC).strftime("%Y-%m-%d")
except (OSError, ValueError, TypeError):
return None
diff --git a/optional-skills/productivity/memento-flashcards/scripts/memento_cards.py b/optional-skills/productivity/memento-flashcards/scripts/memento_cards.py
index 47e41dd3af7..5f9e454d0d7 100644
--- a/optional-skills/productivity/memento-flashcards/scripts/memento_cards.py
+++ b/optional-skills/productivity/memento-flashcards/scripts/memento_cards.py
@@ -12,7 +12,7 @@ import os
import sys
import tempfile
import uuid
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
_HERMES_HOME = Path(os.environ.get("HERMES_HOME", Path.home() / ".hermes"))
@@ -23,7 +23,7 @@ RETIRED_SENTINEL = "9999-12-31T23:59:59+00:00"
def _now() -> datetime:
- return datetime.now(timezone.utc)
+ return datetime.now(UTC)
def _iso(dt: datetime) -> str:
diff --git a/optional-skills/productivity/telephony/scripts/telephony.py b/optional-skills/productivity/telephony/scripts/telephony.py
index 6b8eda4bf81..e7309f01c3a 100644
--- a/optional-skills/productivity/telephony/scripts/telephony.py
+++ b/optional-skills/productivity/telephony/scripts/telephony.py
@@ -27,7 +27,7 @@ import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from email.utils import parsedate_to_datetime
from html import escape as xml_escape
from pathlib import Path
@@ -232,7 +232,7 @@ def _parse_twilio_date(value: str | None) -> datetime | None:
return None
try:
dt = parsedate_to_datetime(value)
- return dt.astimezone(timezone.utc) if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
+ return dt.astimezone(UTC) if dt.tzinfo else dt.replace(tzinfo=UTC)
except Exception:
return None
diff --git a/optional-skills/research/domain-intel/scripts/domain_intel.py b/optional-skills/research/domain-intel/scripts/domain_intel.py
index c25e9286d40..3af88aff508 100644
--- a/optional-skills/research/domain-intel/scripts/domain_intel.py
+++ b/optional-skills/research/domain-intel/scripts/domain_intel.py
@@ -22,7 +22,7 @@ import sys
import urllib.request
import urllib.parse
from concurrent.futures import ThreadPoolExecutor, as_completed
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
# ─── Subdomain Discovery (crt.sh) ──────────────────────────────────────────
@@ -37,12 +37,12 @@ def subdomains(domain, include_expired=False, limit=200):
entries = json.loads(r.read().decode())
seen, results = set(), []
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
for e in entries:
not_after = e.get("not_after", "")
if not include_expired and not_after:
try:
- dt = datetime.strptime(not_after[:19], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=timezone.utc)
+ dt = datetime.strptime(not_after[:19], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=UTC)
if dt <= now:
continue
except ValueError:
@@ -76,7 +76,7 @@ def check_ssl(host, port=443, timeout=10):
def parse_date(s):
for fmt in ("%b %d %H:%M:%S %Y %Z", "%b %d %H:%M:%S %Y %Z"):
try:
- return datetime.strptime(s, fmt).replace(tzinfo=timezone.utc)
+ return datetime.strptime(s, fmt).replace(tzinfo=UTC)
except ValueError:
pass
return None
@@ -97,7 +97,7 @@ def check_ssl(host, port=443, timeout=10):
cert, cipher, proto = s.getpeercert(), s.cipher(), s.version()
not_after = parse_date(cert.get("notAfter", ""))
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
days = (not_after - now).days if not_after else None
is_expired = days is not None and days < 0
@@ -194,10 +194,10 @@ def whois_lookup(domain):
if field in result:
for fmt in ("%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
try:
- dt = datetime.strptime(result[field][:19], fmt).replace(tzinfo=timezone.utc)
+ dt = datetime.strptime(result[field][:19], fmt).replace(tzinfo=UTC)
result[field] = dt.isoformat()
if field == "expiration_date":
- days = (dt - datetime.now(timezone.utc)).days
+ days = (dt - datetime.now(UTC)).days
result["expiration_days_remaining"] = days
result["is_expired"] = days < 0
break
diff --git a/optional-skills/research/rss-feeds/scripts/feed.py b/optional-skills/research/rss-feeds/scripts/feed.py
index 91a5d1b708d..76bf049aa43 100644
--- a/optional-skills/research/rss-feeds/scripts/feed.py
+++ b/optional-skills/research/rss-feeds/scripts/feed.py
@@ -20,7 +20,7 @@ import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from email.utils import parsedate_to_datetime
USER_AGENT = "hermes-agent/1.0 (rss-feeds skill; +https://github.com/NousResearch/hermes-agent)"
@@ -62,8 +62,8 @@ def parse_date(value: str | None) -> str | None:
except ValueError:
return value
if dt.tzinfo is None:
- dt = dt.replace(tzinfo=timezone.utc)
- return dt.astimezone(timezone.utc).isoformat()
+ dt = dt.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).isoformat()
def _text(el, *paths) -> str | None:
@@ -193,9 +193,9 @@ def read(url: str) -> dict:
def filter_entries(entries: list[dict], limit: int, since: str | None) -> list[dict]:
if since:
- cutoff = datetime.fromisoformat(since).replace(tzinfo=timezone.utc) if "T" not in since else datetime.fromisoformat(since)
+ cutoff = datetime.fromisoformat(since).replace(tzinfo=UTC) if "T" not in since else datetime.fromisoformat(since)
if cutoff.tzinfo is None:
- cutoff = cutoff.replace(tzinfo=timezone.utc)
+ cutoff = cutoff.replace(tzinfo=UTC)
entries = [e for e in entries if e["published"] and datetime.fromisoformat(e["published"]) >= cutoff]
entries.sort(key=lambda e: e["published"] or "", reverse=True)
return entries[:limit]
diff --git a/optional-skills/security/oss-forensics/scripts/evidence-store.py b/optional-skills/security/oss-forensics/scripts/evidence-store.py
index 1ac20efd7ff..2b88143545c 100644
--- a/optional-skills/security/oss-forensics/scripts/evidence-store.py
+++ b/optional-skills/security/oss-forensics/scripts/evidence-store.py
@@ -49,7 +49,7 @@ IOC_TYPES = [
def _now_iso():
- return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds") + "Z"
+ return datetime.datetime.now(datetime.UTC).isoformat(timespec="seconds") + "Z"
def _sha256(content: str) -> str:
diff --git a/optional-skills/security/unbroker/scripts/autopilot.py b/optional-skills/security/unbroker/scripts/autopilot.py
index 7461061858e..7cbcc608f94 100644
--- a/optional-skills/security/unbroker/scripts/autopilot.py
+++ b/optional-skills/security/unbroker/scripts/autopilot.py
@@ -48,7 +48,7 @@ def cache_age_days(now: float | None = None) -> float | None:
def _now_iso() -> str:
- return _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+ return _dt.datetime.now(_dt.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
def _min_future_recheck(ledger: dict, at: str) -> str | None:
diff --git a/optional-skills/security/unbroker/scripts/dossier.py b/optional-skills/security/unbroker/scripts/dossier.py
index 50b4c8c6b10..d19f907b752 100644
--- a/optional-skills/security/unbroker/scripts/dossier.py
+++ b/optional-skills/security/unbroker/scripts/dossier.py
@@ -16,7 +16,7 @@ VALID_CONSENT_METHODS = {"self", "written_authorization", "poa"}
def now() -> str:
- return _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+ return _dt.datetime.now(_dt.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
def new_subject_id(full_name: str = "") -> str:
diff --git a/optional-skills/security/unbroker/scripts/ledger.py b/optional-skills/security/unbroker/scripts/ledger.py
index 2483ee6a8e4..b4f8122b88d 100644
--- a/optional-skills/security/unbroker/scripts/ledger.py
+++ b/optional-skills/security/unbroker/scripts/ledger.py
@@ -54,7 +54,7 @@ TRANSITIONS: dict[str, set[str]] = {
def now() -> str:
- return _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+ return _dt.datetime.now(_dt.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
def load(subject_id: str) -> dict:
@@ -116,8 +116,8 @@ VERIFICATION_POLL_DAYS = 1 # how soon to re-poll for an unarrived verificati
def _plus_days(days: int, start: str | None = None) -> str:
- base = _dt.datetime.strptime(start, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=_dt.timezone.utc) \
- if start else _dt.datetime.now(_dt.timezone.utc)
+ base = _dt.datetime.strptime(start, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=_dt.UTC) \
+ if start else _dt.datetime.now(_dt.UTC)
return (base + _dt.timedelta(days=days)).strftime("%Y-%m-%dT%H:%M:%SZ")
diff --git a/plugins/disk-cleanup/disk_cleanup.py b/plugins/disk-cleanup/disk_cleanup.py
index 03d805e603b..f911197ae3e 100755
--- a/plugins/disk-cleanup/disk_cleanup.py
+++ b/plugins/disk-cleanup/disk_cleanup.py
@@ -13,7 +13,7 @@ import functools
import json
import logging
import shutil
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional, Tuple
@@ -61,7 +61,7 @@ def _log(message: str) -> None:
with contextlib.suppress(OSError):
log_file = _state_file("cleanup.log")
log_file.parent.mkdir(parents=True, exist_ok=True)
- ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
+ ts = datetime.now(UTC).strftime("%Y-%m-%d %H:%M:%S")
with open(log_file, "a", encoding="utf-8") as f:
f.write(f"[{ts}] {message}\n")
@@ -189,7 +189,7 @@ def track(path_str: str, category: str, silent: bool = False) -> bool:
tracked = load_tracked()
if any(item["path"] == str(path) for item in tracked):
return False
- tracked.append({"path": str(path), "timestamp": datetime.now(timezone.utc).isoformat(),
+ tracked.append({"path": str(path), "timestamp": datetime.now(UTC).isoformat(),
"category": category, "size": size})
save_tracked(tracked)
_log(f"TRACKED: {path} ({category}, {fmt_size(size)})")
@@ -257,7 +257,7 @@ _STALE_SKIP_NOTE = {"cron-output": "", "test": " — under protected tree"}
def dry_run() -> tuple[list[dict], list[dict]]:
"""Return (auto_delete_list, needs_prompt_list) without touching files."""
auto, prompt = [], []
- for item, p, age in _live_items(load_tracked(), datetime.now(timezone.utc)):
+ for item, p, age in _live_items(load_tracked(), datetime.now(UTC)):
cat = item["category"]
# Stale cron-output entries and protected dirs are skipped by quick(); omit them here too.
if (cat == "cron-output" and guess_category(p) != "cron-output") or _is_protected_dir(p):
@@ -274,7 +274,7 @@ def quick() -> dict[str, Any]:
deleted = freed = 0
new_tracked: list[dict] = []
errors: list[str] = []
- for item, p, age in _live_items(load_tracked(), datetime.now(timezone.utc), log_stale=True):
+ for item, p, age in _live_items(load_tracked(), datetime.now(UTC), log_stale=True):
cat = item["category"]
if cat in _STALE_SKIP_NOTE and (re_cat := guess_category(p)) != cat:
# Misclassified stale entry — drop it rather than delete the file.
diff --git a/plugins/memory/holographic/retrieval.py b/plugins/memory/holographic/retrieval.py
index e528a7742c1..236c1580caa 100644
--- a/plugins/memory/holographic/retrieval.py
+++ b/plugins/memory/holographic/retrieval.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import math
from collections.abc import Callable
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import TYPE_CHECKING
if TYPE_CHECKING:
@@ -209,7 +209,7 @@ class FactRetriever:
return 1.0
try:
ts = datetime.fromisoformat(timestamp_str) if isinstance(timestamp_str, str) else timestamp_str
- age_days = (datetime.now(timezone.utc) - (ts if ts.tzinfo else ts.replace(tzinfo=timezone.utc))).total_seconds() / 86400
+ age_days = (datetime.now(UTC) - (ts if ts.tzinfo else ts.replace(tzinfo=UTC))).total_seconds() / 86400
return 1.0 if age_days < 0 else math.pow(0.5, age_days / self.half_life)
except (ValueError, TypeError):
return 1.0
diff --git a/plugins/memory/retaindb/__init__.py b/plugins/memory/retaindb/__init__.py
index 9d085bbb2fb..22685adaa78 100644
--- a/plugins/memory/retaindb/__init__.py
+++ b/plugins/memory/retaindb/__init__.py
@@ -17,7 +17,7 @@ import sqlite3
import threading
import time
from contextlib import suppress
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Callable
from urllib.parse import quote
@@ -224,7 +224,7 @@ class _WriteQueue:
self._close(*([conn] if conn is not None else []))
def enqueue(self, user_id: str, session_id: str, messages: list) -> None:
- now = datetime.now(timezone.utc).isoformat()
+ now = datetime.now(UTC).isoformat()
with self._shutdown_lock:
if self._shutdown:
return
@@ -406,7 +406,7 @@ class RetainDBMemoryProvider(MemoryProvider):
"""Queue turn for async ingest. Returns immediately."""
if not self._queue or not user_content:
return
- now = datetime.now(timezone.utc).isoformat()
+ now = datetime.now(UTC).isoformat()
self._queue.enqueue(self._user_id, session_id or self._session_id,
[{"role": "user", "content": user_content, "timestamp": now},
{"role": "assistant", "content": assistant_content, "timestamp": now}])
diff --git a/plugins/model-providers/opencode-zen/__init__.py b/plugins/model-providers/opencode-zen/__init__.py
index da334bc48c7..3e3fcd68662 100644
--- a/plugins/model-providers/opencode-zen/__init__.py
+++ b/plugins/model-providers/opencode-zen/__init__.py
@@ -10,6 +10,7 @@ from agent import reasoning_effort as re_
from hermes_cli.version_info import get_version_info
from providers import register_provider
from providers.base import ProviderProfile
+from datetime import UTC
# Attribution headers (same values as OpenRouter / Vercel / Fireworks); via
# default_headers so they survive model switches and credential rotation.
@@ -85,7 +86,7 @@ class OpenCodeGoProfile(ProviderProfile):
reset_at = datetime.fromisoformat(reset_raw) if reset_raw else None
windows.append(AccountUsageWindow(label=label, used_percent=float(window["percent"]), reset_at=reset_at))
return AccountUsageSnapshot(provider=self.name, source="go_usage_api",
- fetched_at=datetime.now(timezone.utc), windows=tuple(windows))
+ fetched_at=datetime.now(UTC), windows=tuple(windows))
def build_api_kwargs_extras(
self, *, reasoning_config: dict | None = None, model: str | None = None, **context
diff --git a/plugins/platforms/a2a/protocol.py b/plugins/platforms/a2a/protocol.py
index bd44a7e71e2..907ab4904a7 100644
--- a/plugins/platforms/a2a/protocol.py
+++ b/plugins/platforms/a2a/protocol.py
@@ -12,7 +12,7 @@ import time
import uuid
from collections import OrderedDict, defaultdict, deque
from concurrent.futures import Future
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Optional
@@ -53,7 +53,7 @@ def max_pingpong_turns() -> int:
def now_iso() -> str:
"""ISO 8601 UTC timestamp with millisecond precision (A2A v1.0)."""
- return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
def build_agent_card(*, name: str, url: str, description: str, skills: Optional[list[dict]] = None,
diff --git a/plugins/platforms/dingtalk/adapter.py b/plugins/platforms/dingtalk/adapter.py
index c5454ee2f35..fb62e53ea99 100644
--- a/plugins/platforms/dingtalk/adapter.py
+++ b/plugins/platforms/dingtalk/adapter.py
@@ -10,7 +10,7 @@ import re
import time
import traceback
import uuid
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Dict, List, Optional, Set
# Optional SDKs: catch broad Exception, not just ImportError — their transitive cryptography
@@ -487,9 +487,9 @@ class DingTalkAdapter(BasePlatformAdapter):
message_id=msg_id)
create_at = getattr(message, "create_at", None)
try:
- timestamp = datetime.fromtimestamp(int(create_at) / 1000, tz=timezone.utc) if create_at else datetime.now(tz=timezone.utc)
+ timestamp = datetime.fromtimestamp(int(create_at) / 1000, tz=UTC) if create_at else datetime.now(tz=UTC)
except (ValueError, OSError, TypeError):
- timestamp = datetime.now(tz=timezone.utc)
+ timestamp = datetime.now(tz=UTC)
logger.debug("[%s] Message from %s in %s: %s", self.name, sender_nick, chat_id[:20] if chat_id else "?", text[:80] if text else "(media)")
await self.handle_message(MessageEvent(text=text, message_type=msg_type, source=source, message_id=msg_id, raw_message=message,
media_urls=media_urls, media_types=media_types, timestamp=timestamp))
@@ -564,7 +564,7 @@ class DingTalkAdapter(BasePlatformAdapter):
"""Get a non-expired session webhook for chat_id (5-minute safety margin)."""
info = self._session_webhooks.get(chat_id)
expired_time_ms = info[1] if info else 0
- if expired_time_ms and expired_time_ms > 0 and int(datetime.now(tz=timezone.utc).timestamp() * 1000) + 5 * 60 * 1000 >= expired_time_ms:
+ if expired_time_ms and expired_time_ms > 0 and int(datetime.now(tz=UTC).timestamp() * 1000) + 5 * 60 * 1000 >= expired_time_ms:
self._session_webhooks.pop(chat_id, None)
return None
return info or None
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.py
index 847267de5a1..519f51cab6e 100644
--- a/plugins/platforms/discord/adapter.py
+++ b/plugins/platforms/discord/adapter.py
@@ -554,7 +554,7 @@ class _DiscordNonConversationalMessageTracker:
def _discord_snowflake_time(snowflake: int) -> dt.datetime:
"""UTC creation time encoded in a Discord snowflake (ms since 2015-01-01 in the top 42 bits)."""
- return dt.datetime.fromtimestamp(((snowflake >> 22) + 1420070400000) / 1000, tz=dt.timezone.utc)
+ return dt.datetime.fromtimestamp(((snowflake >> 22) + 1420070400000) / 1000, tz=dt.UTC)
def _metadata_marks_nonconversational(metadata: Optional[dict[str, Any]]) -> bool:
@@ -2625,7 +2625,7 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceIn
async def _iter_missed_message_backfill_candidates(self, channel_ids: set[str]):
if not self._client:
return
- after = dt.datetime.now(dt.timezone.utc) - dt.timedelta(
+ after = dt.datetime.now(dt.UTC) - dt.timedelta(
seconds=self._missed_message_backfill_window_seconds()
)
limit = self._missed_message_backfill_limit()
@@ -2809,7 +2809,7 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceIn
@staticmethod
def _utc_now_iso() -> str:
import datetime as _dt
- return _dt.datetime.now(_dt.timezone.utc).isoformat()
+ return _dt.datetime.now(_dt.UTC).isoformat()
def _message_channel_ids(self, message: Any) -> tuple[str, Optional[str], Optional[str]]:
channel = getattr(message, "channel", None)
@@ -2992,7 +2992,7 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceIn
def _discord_message_has_active_claim(self, message_id: str) -> bool:
if not message_id:
return False
- cutoff = (dt.datetime.now(dt.timezone.utc) - dt.timedelta(minutes=10)).isoformat()
+ cutoff = (dt.datetime.now(dt.UTC) - dt.timedelta(minutes=10)).isoformat()
def _op(conn):
row = conn.execute(
diff --git a/plugins/platforms/discord/recovery.py b/plugins/platforms/discord/recovery.py
index e052cfd7e6f..1e3bb60fb1d 100644
--- a/plugins/platforms/discord/recovery.py
+++ b/plugins/platforms/discord/recovery.py
@@ -74,7 +74,7 @@ class DiscordRecoveryStore:
channel_id TEXT PRIMARY KEY, last_message_id TEXT NOT NULL, updated_at TEXT NOT NULL
);
""")
- cutoff = (dt.datetime.now(dt.timezone.utc) - dt.timedelta(days=_RETENTION_DAYS)).isoformat()
+ cutoff = (dt.datetime.now(dt.UTC) - dt.timedelta(days=_RETENTION_DAYS)).isoformat()
conn.execute("DELETE FROM discord_messages WHERE updated_at < ?", (cutoff,))
conn.execute("DELETE FROM discord_recovery_scans WHERE COALESCE(completed_at, started_at) < ?", (cutoff,))
conn.execute("DELETE FROM discord_recovery_cursors WHERE updated_at < ?", (cutoff,))
diff --git a/plugins/platforms/ntfy/adapter.py b/plugins/platforms/ntfy/adapter.py
index 4c9ef036163..01937b8343a 100644
--- a/plugins/platforms/ntfy/adapter.py
+++ b/plugins/platforms/ntfy/adapter.py
@@ -14,7 +14,7 @@ import json
import logging
import time
import uuid
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Dict, List, Optional
try:
@@ -256,9 +256,9 @@ class NtfyAdapter(BasePlatformAdapter):
topic = event.get("topic") or self._topic
source = self.build_source(
chat_id=topic, chat_name=topic, chat_type="dm", user_id=topic, user_name=topic, message_id=msg_id)
- unix_ts, timestamp = event.get("time"), datetime.now(tz=timezone.utc)
+ unix_ts, timestamp = event.get("time"), datetime.now(tz=UTC)
try:
- timestamp = datetime.fromtimestamp(int(unix_ts), tz=timezone.utc) if unix_ts else timestamp
+ timestamp = datetime.fromtimestamp(int(unix_ts), tz=UTC) if unix_ts else timestamp
except (ValueError, OSError, TypeError):
pass
message_event = MessageEvent(
diff --git a/plugins/platforms/photon/adapter.py b/plugins/platforms/photon/adapter.py
index 2d09cce06cf..25546d3d685 100644
--- a/plugins/platforms/photon/adapter.py
+++ b/plugins/platforms/photon/adapter.py
@@ -18,7 +18,7 @@ import signal
import subprocess
import sys
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import TYPE_CHECKING, Any, AsyncIterator, Callable, Dict, List, Optional, Tuple
from urllib.parse import urlparse
@@ -426,9 +426,9 @@ def _is_richlink_preview_content(content: dict[str, Any]) -> bool:
def _parse_timestamp(ts_str: str) -> datetime:
try:
- return datetime.fromisoformat(ts_str) if ts_str else datetime.now(tz=timezone.utc)
+ return datetime.fromisoformat(ts_str) if ts_str else datetime.now(tz=UTC)
except ValueError:
- return datetime.now(tz=timezone.utc)
+ return datetime.now(tz=UTC)
_Normalized = tuple[str, MessageType, list[str], list[str]] # text, type, media_urls, media_types
diff --git a/plugins/platforms/raft/adapter.py b/plugins/platforms/raft/adapter.py
index 345b0cb4030..29ac8c66e88 100644
--- a/plugins/platforms/raft/adapter.py
+++ b/plugins/platforms/raft/adapter.py
@@ -8,7 +8,7 @@ if unset). The bridge owns Raft message cursors/bodies; the agent uses the Raft
from __future__ import annotations
from collections import deque
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
import functools
import hmac
import json
@@ -124,7 +124,7 @@ def _make_activity_event(*, hook_event_name: str, session_id: Any, status: str =
event: dict[str, Any] = {"schema": ACTIVITY_EVENT_SCHEMA, "eventId": f"hermes-{uuid.uuid4()}",
"sessionId": _safe_scalar(session_id, "unknown") or "unknown",
"hookEventName": hook_event_name, "status": "error" if status == "error" else "ok",
- "occurredAt": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")}
+ "occurredAt": datetime.now(UTC).isoformat().replace("+00:00", "Z")}
for key, raw in (("toolName", tool_name), ("errorClass", error_class)):
if safe := _safe_scalar(raw):
event[key] = safe
diff --git a/plugins/platforms/simplex/adapter.py b/plugins/platforms/simplex/adapter.py
index 8e0d5f1ac00..4591bdc4294 100644
--- a/plugins/platforms/simplex/adapter.py
+++ b/plugins/platforms/simplex/adapter.py
@@ -18,7 +18,7 @@ import os
import random
import re
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Dict, List, Optional
@@ -385,9 +385,9 @@ class SimplexAdapter(BasePlatformAdapter):
MessageType.DOCUMENT)
ts_str = meta.get("itemTs") or meta.get("createdAt", "")
try:
- timestamp = datetime.fromisoformat(ts_str) if ts_str else datetime.now(tz=timezone.utc)
+ timestamp = datetime.fromisoformat(ts_str) if ts_str else datetime.now(tz=UTC)
except (ValueError, AttributeError):
- timestamp = datetime.now(tz=timezone.utc)
+ timestamp = datetime.now(tz=UTC)
msg_event = MessageEvent(
source=source, text=text or "", message_type=msg_type, media_urls=media_urls,
media_types=media_types, timestamp=timestamp, raw_message=chat_item)
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index 40d5904004c..bdcea5d45f1 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -11,7 +11,7 @@ import html as _html
import re
import time
from contextvars import ContextVar
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Awaitable, Callable, Dict, Iterator, List, Optional, Set
from hermes_cli import setup_platforms
@@ -6343,7 +6343,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):
session_entry = store.get_or_create_session(self._telegram_group_observe_shared_source(event.source))
entry = {
"role": "user", "content": self._telegram_group_observe_attributed_text(event),
- "timestamp": datetime.now(tz=timezone.utc).isoformat(), "observed": True}
+ "timestamp": datetime.now(tz=UTC).isoformat(), "observed": True}
if event.message_id:
entry["message_id"] = str(event.message_id)
self._accept_update()
diff --git a/plugins/platforms/wecom/adapter.py b/plugins/platforms/wecom/adapter.py
index d893ea38439..63290237503 100644
--- a/plugins/platforms/wecom/adapter.py
+++ b/plugins/platforms/wecom/adapter.py
@@ -13,7 +13,7 @@ import logging
import re
import time
import uuid
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Dict, List, Optional, Tuple
try:
@@ -457,7 +457,7 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, OwnAcc
message_id=msg_id)
event = MessageEvent(
text=text, message_type=message_type, source=source, raw_message=payload, message_id=msg_id, media_urls=media_urls, media_types=media_types,
- reply_to_message_id=f"quote:{msg_id}" if has_reply_context else None, reply_to_text=reply_text if has_reply_context else None, timestamp=datetime.now(tz=timezone.utc),
+ reply_to_message_id=f"quote:{msg_id}" if has_reply_context else None, reply_to_text=reply_text if has_reply_context else None, timestamp=datetime.now(tz=UTC),
)
# Only plain text is batched, EXCEPT attachment-only messages, which are held so the
# trailing text callback merges instead of "interrupting" a run the attachment spawned.
diff --git a/plugins/teams_pipeline/models.py b/plugins/teams_pipeline/models.py
index c13269e47ad..0ce903d4e21 100644
--- a/plugins/teams_pipeline/models.py
+++ b/plugins/teams_pipeline/models.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from dataclasses import dataclass, field, fields
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Callable, ClassVar, Literal
@@ -20,11 +20,11 @@ def _parse_datetime(value: Any) -> datetime | None:
if text.endswith("Z"):
text = f"{text[:-1]}+00:00"
parsed = datetime.fromisoformat(text)
- return parsed.replace(tzinfo=timezone.utc) if parsed.tzinfo is None else parsed
+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed
def _serialize_datetime(value: datetime | None) -> str | None:
- return None if value is None else value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
+ return None if value is None else value.astimezone(UTC).isoformat().replace("+00:00", "Z")
def _camel(name: str) -> str:
diff --git a/plugins/teams_pipeline/store.py b/plugins/teams_pipeline/store.py
index dd5302d2ef0..1bc47c49224 100644
--- a/plugins/teams_pipeline/store.py
+++ b/plugins/teams_pipeline/store.py
@@ -7,7 +7,7 @@ import json
import os
import threading
from copy import deepcopy
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from functools import partialmethod
from pathlib import Path
from tempfile import NamedTemporaryFile
@@ -22,7 +22,7 @@ _BUCKETS = ("subscriptions", "notification_receipts", "event_timestamps", "jobs"
def _utc_now_iso() -> str:
- return datetime.now(timezone.utc).isoformat()
+ return datetime.now(UTC).isoformat()
def resolve_teams_pipeline_store_path(path: str | Path | None = None) -> Path:
diff --git a/plugins/teams_pipeline/subscriptions.py b/plugins/teams_pipeline/subscriptions.py
index 22ffc5f25fc..0e1867c3197 100644
--- a/plugins/teams_pipeline/subscriptions.py
+++ b/plugins/teams_pipeline/subscriptions.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from os import getenv
from typing import Any
@@ -18,7 +18,7 @@ def build_graph_client() -> MicrosoftGraphClient:
def _utc_now() -> datetime:
- return datetime.now(timezone.utc)
+ return datetime.now(UTC)
def utc_timestamp(hours_from_now: int = 0, *, base: datetime | None = None) -> str:
diff --git a/pm/network.py b/pm/network.py
index c110a0a7d76..eca4961d916 100644
--- a/pm/network.py
+++ b/pm/network.py
@@ -9,7 +9,7 @@ import socket
import ssl
import time
import urllib.error
-from datetime import timezone
+from datetime import timezone, UTC
from email.utils import parsedate_to_datetime
from typing import Callable, TypeVar
@@ -51,7 +51,7 @@ def _delay(exc: Exception, attempt: int) -> float:
try:
when = parsedate_to_datetime(value)
if when.tzinfo is None:
- when = when.replace(tzinfo=timezone.utc)
+ when = when.replace(tzinfo=UTC)
retry_after = when.timestamp() - time.time()
except (TypeError, ValueError, OverflowError):
retry_after = 0.0
diff --git a/pm/receipt.py b/pm/receipt.py
index 34cca627827..95df41457ac 100644
--- a/pm/receipt.py
+++ b/pm/receipt.py
@@ -43,7 +43,7 @@ import json
import os
import time
import uuid
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Optional
@@ -118,7 +118,7 @@ def _ambient_update_id() -> Optional[str]:
def _utc_now_iso() -> str:
- return datetime.now(timezone.utc).isoformat()
+ return datetime.now(UTC).isoformat()
def _receipt_dir() -> Path:
diff --git a/ruff.strict.toml b/ruff.strict.toml
index 5a7221f726e..7cdb36ab7d6 100644
--- a/ruff.strict.toml
+++ b/ruff.strict.toml
@@ -365,7 +365,7 @@ select = [
"UP011",
"UP012",
"UP014",
- # "UP017",
+ "UP017",
"UP018",
"UP019",
"UP020",
diff --git a/scripts/build_model_catalog.py b/scripts/build_model_catalog.py
index 1bcf0e369e5..076f7e45e06 100755
--- a/scripts/build_model_catalog.py
+++ b/scripts/build_model_catalog.py
@@ -25,7 +25,7 @@ from __future__ import annotations
import json
import os
import sys
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, REPO_ROOT)
@@ -61,7 +61,7 @@ def _nous_entry(mid: str) -> dict:
def build_catalog() -> dict:
return {
"version": CATALOG_VERSION,
- "updated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
+ "updated_at": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
"metadata": {
"source": "hermes-agent repo",
"docs": "https://hermes-agent.nousresearch.com/docs/reference/model-catalog",
diff --git a/scripts/build_skills_index.py b/scripts/build_skills_index.py
index f43b6b8abe8..2a17aa605df 100755
--- a/scripts/build_skills_index.py
+++ b/scripts/build_skills_index.py
@@ -22,7 +22,7 @@ import sys
import time
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
# Allow importing from repo root
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -440,7 +440,7 @@ def main():
# Healthy — only now write the index out for the docs build to consume.
index = {
"version": INDEX_VERSION,
- "generated_at": datetime.now(timezone.utc).isoformat(),
+ "generated_at": datetime.now(UTC).isoformat(),
"skill_count": len(deduped),
"skills": deduped,
}
diff --git a/scripts/bundles/desktop_prepare.py b/scripts/bundles/desktop_prepare.py
index 6ba8b465734..1351a850012 100644
--- a/scripts/bundles/desktop_prepare.py
+++ b/scripts/bundles/desktop_prepare.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import argparse
from dataclasses import asdict, dataclass
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
import hashlib
import json
import re
@@ -150,7 +150,7 @@ class BuildRequest:
canary = re.fullmatch(r"v\d+\.\d+\.\d+\+canary\.(20\d{6}T\d{6}Z)", tag)
if canary:
release_epoch = int(datetime.strptime(canary.group(1), "%Y%m%dT%H%M%SZ")
- .replace(tzinfo=timezone.utc).timestamp())
+ .replace(tzinfo=UTC).timestamp())
else:
claim_tag = os.environ.get("RELEASE_CLAIM_TAG", "")
# The payload version stays plain; the claim must name the same
diff --git a/scripts/docker_rebootstrap_nous_session.py b/scripts/docker_rebootstrap_nous_session.py
index ce64c2899cd..93439d6595c 100644
--- a/scripts/docker_rebootstrap_nous_session.py
+++ b/scripts/docker_rebootstrap_nous_session.py
@@ -40,7 +40,7 @@ import json
import os
import sys
import tempfile
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Optional
# Env var the orchestrator sets to the re-seed payload. Deliberately DISTINCT
@@ -113,7 +113,7 @@ def _parse_timestamp(value: Any) -> Optional[datetime]:
if parsed.tzinfo is None:
return None
try:
- return parsed.astimezone(timezone.utc)
+ return parsed.astimezone(UTC)
except (OverflowError, ValueError):
return None
diff --git a/scripts/e2e_shared_metrics_staging.py b/scripts/e2e_shared_metrics_staging.py
index f4aa9281e08..fe3d7c5dca8 100644
--- a/scripts/e2e_shared_metrics_staging.py
+++ b/scripts/e2e_shared_metrics_staging.py
@@ -15,7 +15,7 @@ import os
import sys
import tempfile
import uuid
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
@@ -61,7 +61,7 @@ def main() -> int:
outbox_directory=scratch / "outbox",
)
- today = datetime.now(timezone.utc).date().isoformat()
+ today = datetime.now(UTC).date().isoformat()
# The generator only exports COMPLETED periods, so the realistic E2E
# package is yesterday's. It also has to be: the consent gate only
# releases a package once its whole period is confirmed consented, and
@@ -69,7 +69,7 @@ def main() -> int:
from datetime import timedelta
period_day = (
- datetime.now(timezone.utc).date() - timedelta(days=1)
+ datetime.now(UTC).date() - timedelta(days=1)
).isoformat()
# Open the consent window before the period, confirm it after — exactly
@@ -84,7 +84,7 @@ def main() -> int:
reconcile_send_consent(
connection,
True,
- now=datetime.now(timezone.utc) - timedelta(days=2),
+ now=datetime.now(UTC) - timedelta(days=2),
)
reconcile_send_consent(connection, True)
real_install_id = str(uuid.uuid4())
@@ -99,7 +99,7 @@ def main() -> int:
"schema_version": "hermes.shared_metrics.v2",
"package_id": package_id,
"install_id": real_install_id,
- "generated_at": datetime.now(timezone.utc).isoformat().replace(
+ "generated_at": datetime.now(UTC).isoformat().replace(
"+00:00", "Z"
),
"period_start": f"{period_day}T00:00:00Z",
diff --git a/scripts/release.py b/scripts/release.py
index 9def06b4cdc..d8198f03168 100755
--- a/scripts/release.py
+++ b/scripts/release.py
@@ -14,7 +14,7 @@ import shutil
import subprocess
import sys
from collections import defaultdict
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
# Bootstrap the repo root onto sys.path so this script can import the
@@ -488,7 +488,7 @@ def cmd_canary(args) -> None:
canary — the skip-if-no-new-commits gate lives HERE, not in workflow
YAML.
"""
- date_utc = args.date or datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
+ date_utc = args.date or datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
push_remote = resolve_push_remote(args.remote)
gh_repo = remote_github_repo(push_remote)
if not gh_repo:
@@ -576,7 +576,7 @@ def prune_old_canaries(args) -> None:
"""
push_remote = resolve_push_remote(args.remote)
gh_repo = remote_github_repo(push_remote)
- cutoff = (datetime.now(timezone.utc) - timedelta(days=14)).strftime("%Y%m%d")
+ cutoff = (datetime.now(UTC) - timedelta(days=14)).strftime("%Y%m%d")
tags = git("tag", "--list", "v*+canary.*", "--sort=-creatordate")
doomed = []
diff --git a/scripts/releases/channel_releases.py b/scripts/releases/channel_releases.py
index 5c2d04a05be..443b62923c3 100644
--- a/scripts/releases/channel_releases.py
+++ b/scripts/releases/channel_releases.py
@@ -8,7 +8,7 @@ import os
from pathlib import Path
import subprocess
import tempfile
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from hermes_cli.release_channels import (
ChannelError, build_prefix, canonical_json, validate_identity,
@@ -104,7 +104,7 @@ def canary_windows_version(tag: str) -> str:
stamp = canary_timestamp(tag)
if stamp is None:
raise ChannelError("Invalid canary release identity")
- instant = datetime.strptime(stamp, "%Y%m%dT%H%M%SZ").replace(tzinfo=timezone.utc)
+ instant = datetime.strptime(stamp, "%Y%m%dT%H%M%SZ").replace(tzinfo=UTC)
return f"{instant.year % 100}.{int(f'{instant.month:02d}{instant.day:02d}')}.{instant.hour}.{int(f'{instant.minute:02d}{instant.second:02d}')}"
diff --git a/scripts/releases/commit_build.py b/scripts/releases/commit_build.py
index c6fde707d3b..8c8ccfcfd6c 100644
--- a/scripts/releases/commit_build.py
+++ b/scripts/releases/commit_build.py
@@ -7,7 +7,7 @@ import re
import shlex
import subprocess
import tomllib
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
WORKFLOW = "desktop-bundled-release.yml"
@@ -87,7 +87,7 @@ def receipt_tag(kind: str, version: str, created_at: str, run_id: str) -> str:
if not re.fullmatch(r"[1-9][0-9]{0,19}", run_id):
raise ValueError("Build receipt run ID is invalid")
try:
- instant = datetime.fromisoformat(created_at).astimezone(timezone.utc)
+ instant = datetime.fromisoformat(created_at).astimezone(UTC)
except (AttributeError, ValueError) as error:
raise ValueError("Build receipt creation time is invalid") from error
if instant.microsecond or created_at != instant.strftime("%Y-%m-%dT%H:%M:%SZ"):
diff --git a/scripts/releases/r2.py b/scripts/releases/r2.py
index dd515d9f2f3..7c4e8afe319 100644
--- a/scripts/releases/r2.py
+++ b/scripts/releases/r2.py
@@ -10,7 +10,7 @@ import os
import re
import sys
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Callable, Iterable, cast
from urllib.parse import quote, urlparse
@@ -150,7 +150,7 @@ def encode_key_path(key: str) -> str:
def amz_timestamp() -> str:
- return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
+ return datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
class R2RequestError(Exception):
@@ -737,12 +737,12 @@ def parse_list_xml(xml: str) -> dict:
if "." in text:
return int(
datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%fZ")
- .replace(tzinfo=timezone.utc)
+ .replace(tzinfo=UTC)
.timestamp()
)
return int(
datetime.strptime(text, "%Y-%m-%dT%H:%M:%SZ")
- .replace(tzinfo=timezone.utc)
+ .replace(tzinfo=UTC)
.timestamp()
)
diff --git a/scripts/releases/sequencer.py b/scripts/releases/sequencer.py
index 4aa6e130e50..4b2c1a44fc6 100644
--- a/scripts/releases/sequencer.py
+++ b/scripts/releases/sequencer.py
@@ -12,7 +12,7 @@ import subprocess
import sys
import tempfile
import time
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
from scripts.releases.versioning import (
@@ -119,7 +119,7 @@ def classify_runs(runs: list[dict], *, claimed_at: datetime | None = None,
if not runs:
if claimed_at is None:
raise ValueError("A claim without a workflow needs its immutable claim time")
- now = now or datetime.now(timezone.utc)
+ now = now or datetime.now(UTC)
return ("running", None) if now < claimed_at + CLAIM_GRACE else ("burned", None)
run_ids = {row.get("id") for row in runs}
if len(run_ids) != 1 or None in run_ids:
@@ -281,7 +281,7 @@ def discover(repository: str, run=output) -> list[dict]:
if row.get("head_branch") == claim_tag and row.get("head_sha") == commit]
state, retry = classify_runs(
matching_runs,
- claimed_at=datetime.fromtimestamp(claim_epoch, tz=timezone.utc),
+ claimed_at=datetime.fromtimestamp(claim_epoch, tz=UTC),
has_draft=release is not None,
)
diff --git a/scripts/releases/stable.py b/scripts/releases/stable.py
index 9df21127c0a..857749ad7e4 100644
--- a/scripts/releases/stable.py
+++ b/scripts/releases/stable.py
@@ -11,7 +11,7 @@ import tempfile
import tomllib
import urllib.error
import urllib.request
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from urllib.parse import unquote, urlsplit
@@ -132,8 +132,8 @@ def require_smokes_match_claim(manifest: dict, *, skip_tests: bool) -> None:
def stable_windows_version(epoch: object) -> str:
if isinstance(epoch, bool) or not isinstance(epoch, int) or epoch < 0:
raise ValueError("Stable release epoch must be a non-negative integer")
- instant = datetime.fromtimestamp(epoch, tz=timezone.utc)
- start = datetime(instant.year, 1, 1, tzinfo=timezone.utc)
+ instant = datetime.fromtimestamp(epoch, tz=UTC)
+ start = datetime(instant.year, 1, 1, tzinfo=UTC)
hour_of_year = (instant - start).days * 24 + instant.hour
second_of_hour = instant.minute * 60 + instant.second
return f"{instant.year}.{hour_of_year}.{second_of_hour}.0"
diff --git a/scripts/write_install_stamp.py b/scripts/write_install_stamp.py
index 16ba1ffca9e..7aec97f129a 100644
--- a/scripts/write_install_stamp.py
+++ b/scripts/write_install_stamp.py
@@ -31,7 +31,7 @@ import os
import re
import subprocess
import sys
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
# Bootstrap the repo root onto sys.path so the canary tag shape can come
@@ -255,7 +255,7 @@ def build_stamp(
"commit": commit,
"commitDate": commit_date,
"branch": branch,
- "builtAt": datetime.now(timezone.utc).isoformat(),
+ "builtAt": datetime.now(UTC).isoformat(),
"dirty": dirty,
"source": source,
"distribution": distribution,
diff --git a/skills/productivity/docx/scripts/docx_comments.py b/skills/productivity/docx/scripts/docx_comments.py
index 6888840dd4b..0beeddde7d0 100644
--- a/skills/productivity/docx/scripts/docx_comments.py
+++ b/skills/productivity/docx/scripts/docx_comments.py
@@ -175,7 +175,7 @@ def add_comment_xml(doc, runs, text, author, initials) -> str:
encoding="UTF-8", standalone=True)
part.__class__ = type("CommentsXmlPart", (Part,),
{"blob": property(lambda self: _blob(self))})
- now = _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+ now = _dt.datetime.now(_dt.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
comment = etree.SubElement(root, q("comment"))
comment.set(q("id"), cid)
comment.set(q("author"), author)
diff --git a/skills/productivity/google-workspace/scripts/google_api.py b/skills/productivity/google-workspace/scripts/google_api.py
index 3276e54e20a..9d76a17f6da 100644
--- a/skills/productivity/google-workspace/scripts/google_api.py
+++ b/skills/productivity/google-workspace/scripts/google_api.py
@@ -27,7 +27,7 @@ import os
import shutil
import subprocess
import sys
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from email.mime.text import MIMEText
from pathlib import Path
@@ -523,7 +523,7 @@ def gmail_modify(args):
def calendar_list(args):
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
time_min = _datetime_with_timezone(args.start or now.isoformat())
time_max = _datetime_with_timezone(args.end or (now + timedelta(days=7)).isoformat())
diff --git a/skills/productivity/google-workspace/scripts/gws_bridge.py b/skills/productivity/google-workspace/scripts/gws_bridge.py
index d990797bacb..fa28bdb38cd 100755
--- a/skills/productivity/google-workspace/scripts/gws_bridge.py
+++ b/skills/productivity/google-workspace/scripts/gws_bridge.py
@@ -7,7 +7,7 @@ import json
import os
import subprocess
import sys
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
# Ensure sibling modules (_hermes_home) are importable when run standalone.
@@ -71,8 +71,8 @@ def refresh_token(token_data: dict) -> dict:
token_data["token"] = result["access_token"]
token_data["expiry"] = datetime.fromtimestamp(
- datetime.now(timezone.utc).timestamp() + result["expires_in"],
- tz=timezone.utc,
+ datetime.now(UTC).timestamp() + result["expires_in"],
+ tz=UTC,
).isoformat()
get_token_path().write_text(
@@ -93,7 +93,7 @@ def get_valid_token() -> str:
expiry = token_data.get("expiry", "")
if expiry:
exp_dt = datetime.fromisoformat(expiry)
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
if now >= exp_dt:
token_data = refresh_token(token_data)
diff --git a/tests/agent/test_account_usage_fetch.py b/tests/agent/test_account_usage_fetch.py
index 439ca1ae18b..a207b96847d 100644
--- a/tests/agent/test_account_usage_fetch.py
+++ b/tests/agent/test_account_usage_fetch.py
@@ -2,7 +2,7 @@ import concurrent.futures
import contextvars
import threading
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
import pytest
@@ -114,7 +114,7 @@ def test_fetch_account_usage_codex(monkeypatch):
assert len(snapshot.windows) == 2
assert snapshot.windows[0].label == "Session"
assert snapshot.windows[0].used_percent == 15.0
- assert snapshot.windows[0].reset_at == datetime.fromtimestamp(1_900_000_000, tz=timezone.utc)
+ assert snapshot.windows[0].reset_at == datetime.fromtimestamp(1_900_000_000, tz=UTC)
assert "Credits balance: $12.50" in snapshot.details
@@ -130,7 +130,7 @@ def test_fetch_account_usage_reaches_registered_plugin_profile_and_fails_open(mo
"""A profile registered through the public registry (as a plugin does) feeds /usage; a profile
without the hook, or one whose hook raises, is indistinguishable from today's empty block."""
snapshot = AccountUsageSnapshot(
- provider="plugin-usage", source="plugin", fetched_at=datetime.now(timezone.utc),
+ provider="plugin-usage", source="plugin", fetched_at=datetime.now(UTC),
details=("Credit: 10/100",),
)
profile = _UsageProfile(snapshot)
@@ -146,10 +146,10 @@ def test_fetch_account_usage_reaches_registered_plugin_profile_and_fails_open(mo
def test_fetch_account_usage_prefers_builtin_fetcher_over_profile(monkeypatch):
builtin = AccountUsageSnapshot(
- provider="openrouter", source="builtin", fetched_at=datetime.now(timezone.utc),
+ provider="openrouter", source="builtin", fetched_at=datetime.now(UTC),
)
profile = _UsageProfile(
- AccountUsageSnapshot(provider="openrouter", source="plugin", fetched_at=datetime.now(timezone.utc)),
+ AccountUsageSnapshot(provider="openrouter", source="plugin", fetched_at=datetime.now(UTC)),
name="openrouter",
)
monkeypatch.setattr("agent.account_usage._USAGE_FETCHERS", {"openrouter": lambda base_url, api_key: builtin})
@@ -258,7 +258,7 @@ def test_plugin_usage_hook_is_bounded_and_fails_open(monkeypatch):
def fetch_account_usage(self, *, base_url=None, api_key=None):
started.set()
time.sleep(5)
- return AccountUsageSnapshot(provider=self.name, source="late", fetched_at=datetime.now(timezone.utc))
+ return AccountUsageSnapshot(provider=self.name, source="late", fetched_at=datetime.now(UTC))
_register_profile(monkeypatch, _Hang(name="plugin-hang"))
monkeypatch.setattr(account_usage, "PLUGIN_USAGE_HOOK_DEADLINE_S", 0.3)
diff --git a/tests/agent/test_account_usage_pool_fetch.py b/tests/agent/test_account_usage_pool_fetch.py
index d3d1a2a96d2..11d576e2611 100644
--- a/tests/agent/test_account_usage_pool_fetch.py
+++ b/tests/agent/test_account_usage_pool_fetch.py
@@ -10,7 +10,7 @@ from __future__ import annotations
import base64
import json
import threading
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import httpx
@@ -67,7 +67,7 @@ class _LoopbackUsageServer:
def _usage_payload(session_used: float = 20.0, weekly_used: float = 5.0) -> dict:
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
return {
"plan_type": "pro",
"rate_limit": {
diff --git a/tests/agent/test_command_token_source.py b/tests/agent/test_command_token_source.py
index 78bd86ec1ff..0e10398da42 100644
--- a/tests/agent/test_command_token_source.py
+++ b/tests/agent/test_command_token_source.py
@@ -25,6 +25,7 @@ from agent.command_token_source import (
_mint,
build_command_token_provider,
)
+from datetime import UTC
class TestMinting:
@@ -246,7 +247,7 @@ class TestAbsoluteExpiry:
from datetime import datetime, timedelta, timezone
return (
- datetime.now(timezone.utc) + timedelta(seconds=seconds_from_now)
+ datetime.now(UTC) + timedelta(seconds=seconds_from_now)
).isoformat()
def test_iso_expiry_yields_a_ttl(self):
diff --git a/tests/agent/test_context_compressor_temporal_anchoring.py b/tests/agent/test_context_compressor_temporal_anchoring.py
index 8e1af4ec35b..8502f7b47dd 100644
--- a/tests/agent/test_context_compressor_temporal_anchoring.py
+++ b/tests/agent/test_context_compressor_temporal_anchoring.py
@@ -11,7 +11,7 @@ summarizer prompt. ``test_context_compressor_summary_continuity`` already
proves ``compress()`` routes into ``_generate_summary``.
"""
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from unittest.mock import MagicMock, patch
import hermes_time
@@ -46,7 +46,7 @@ def _turns():
def _fixed_now():
- return datetime(2026, 6, 7, 12, 0, tzinfo=timezone.utc)
+ return datetime(2026, 6, 7, 12, 0, tzinfo=UTC)
@@ -76,7 +76,7 @@ def test_clock_failure_omits_rule_but_compaction_still_runs():
def test_anchoring_rule_uses_date_from_hermes_time_now():
"""The date is taken from hermes_time.now(), which respects the user's TZ."""
compressor = _compressor()
- fixed = datetime(2025, 12, 31, 23, 30, tzinfo=timezone.utc)
+ fixed = datetime(2025, 12, 31, 23, 30, tzinfo=UTC)
with patch.object(hermes_time, "now", lambda: fixed), patch(
"agent.context_compressor.call_llm", return_value=_response("summary")
) as mock_call:
diff --git a/tests/agent/test_credential_pool.py b/tests/agent/test_credential_pool.py
index 4745e178654..ab8234d1448 100644
--- a/tests/agent/test_credential_pool.py
+++ b/tests/agent/test_credential_pool.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import base64
import json
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
import pytest
@@ -995,7 +995,7 @@ def test_load_pool_falls_back_to_os_environ_when_dotenv_empty(tmp_path, monkeypa
def test_load_pool_mirrors_nous_invoke_jwt_agent_key_runtime_api_key(tmp_path, monkeypatch):
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
- expires_at = datetime.fromtimestamp(time.time() + 3600, tz=timezone.utc).isoformat()
+ expires_at = datetime.fromtimestamp(time.time() + 3600, tz=UTC).isoformat()
token = _jwt_with_claims({
"sub": "test-user",
"scope": ["inference:invoke"],
@@ -1054,7 +1054,7 @@ def test_nous_runtime_api_key_rejects_opaque_agent_key():
agent_key="opaque-agent-key",
agent_key_expires_at=datetime.fromtimestamp(
time.time() + 3600,
- tz=timezone.utc,
+ tz=UTC,
).isoformat(),
extra={"scope": "inference:invoke"},
)
diff --git a/tests/agent/test_curator.py b/tests/agent/test_curator.py
index 8ababef98cd..3b0c33435e5 100644
--- a/tests/agent/test_curator.py
+++ b/tests/agent/test_curator.py
@@ -9,7 +9,7 @@ from __future__ import annotations
import importlib
import json
import threading
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
import pytest
@@ -170,7 +170,7 @@ def test_non_positive_interval_hours_falls_back_to_default(curator_env, monkeypa
re-running the review pass each time; it must fall back to the default interval instead."""
c = curator_env["curator"]
monkeypatch.setattr(c, "_load_config", lambda: {"interval_hours": bad_hours})
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
c.save_state({"last_run_at": (now - timedelta(minutes=1)).isoformat()})
assert c.get_interval_hours() == c.DEFAULT_INTERVAL_HOURS
@@ -200,7 +200,7 @@ def test_pinned_skill_is_never_touched(curator_env):
skills_dir = curator_env["home"] / "skills"
_write_skill(skills_dir, "precious")
- super_old = (datetime.now(timezone.utc) - timedelta(days=365)).isoformat()
+ super_old = (datetime.now(UTC) - timedelta(days=365)).isoformat()
data = u.load_usage()
data["precious"] = u._empty_record()
data["precious"]["created_by"] = "agent"
@@ -223,7 +223,7 @@ def test_pinned_skill_is_never_touched(curator_env):
def _backdate(u, name: str, days: int, *, use_count: int = 1):
"""Write an agent-created usage record whose activity is *days* old."""
- ts = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat()
+ ts = (datetime.now(UTC) - timedelta(days=days)).isoformat()
data = u.load_usage()
data[name] = u._empty_record()
data[name]["created_by"] = "agent"
@@ -449,7 +449,7 @@ def test_prune_builtins_still_archives_bundled_via_deterministic_pass(
skills_dir = _write_bundled_and_agent(curator_env, u)
_enable_prune_builtins(curator_env, monkeypatch)
- super_old = (datetime.now(timezone.utc) - timedelta(days=200)).isoformat()
+ super_old = (datetime.now(UTC) - timedelta(days=200)).isoformat()
data = u.load_usage()
data["bundled-fixture"] = u._empty_record()
data["bundled-fixture"]["last_used_at"] = super_old
@@ -496,7 +496,7 @@ def test_protected_builtin_never_archived_even_when_stale(curator_env, monkeypat
_enable_prune_builtins(curator_env, monkeypatch)
# Force a record that is far past the archive cutoff.
- super_old = (datetime.now(timezone.utc) - timedelta(days=500)).isoformat()
+ super_old = (datetime.now(UTC) - timedelta(days=500)).isoformat()
data = u.load_usage()
data[name] = u._empty_record()
data[name]["last_used_at"] = super_old
@@ -522,12 +522,12 @@ def test_preseeded_never_used_builtin_is_reanchored_not_staled(curator_env, monk
_write_skill(skills_dir, "bundled-helper")
(skills_dir / ".bundled_manifest").write_text("bundled-helper:abc\n", encoding="utf-8")
_enable_prune_builtins(curator_env, monkeypatch)
- super_old = (datetime.now(timezone.utc) - timedelta(days=365)).isoformat()
+ super_old = (datetime.now(UTC) - timedelta(days=365)).isoformat()
data = u.load_usage()
data["bundled-helper"] = {**u._empty_record(), "created_at": super_old, "state": u.STATE_STALE}
u.save_usage(data)
- t0 = datetime.now(timezone.utc)
+ t0 = datetime.now(UTC)
counts = c.apply_automatic_transitions(now=t0)
assert (counts["marked_stale"], counts["archived"], counts["seeded"]) == (0, 0, 1)
rec = u.get_record("bundled-helper")
diff --git a/tests/agent/test_curator_activity.py b/tests/agent/test_curator_activity.py
index f5607b9875e..8ab7347565a 100644
--- a/tests/agent/test_curator_activity.py
+++ b/tests/agent/test_curator_activity.py
@@ -1,7 +1,7 @@
"""Regression tests for curator skill activity timestamps."""
import importlib
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
import pytest
@@ -36,7 +36,7 @@ def test_recent_view_activity_prevents_false_stale_transition(curator_modules, m
skills_dir = home / "skills"
_write_skill(skills_dir, "recently-viewed")
- now = datetime(2026, 4, 30, tzinfo=timezone.utc)
+ now = datetime(2026, 4, 30, tzinfo=UTC)
created_at = (now - timedelta(days=60)).isoformat()
last_viewed_at = (now - timedelta(days=1)).isoformat()
skill_usage.save_usage({
diff --git a/tests/agent/test_curator_classification.py b/tests/agent/test_curator_classification.py
index dc0b525efe6..ebb176c06fd 100644
--- a/tests/agent/test_curator_classification.py
+++ b/tests/agent/test_curator_classification.py
@@ -14,7 +14,7 @@ which misled users into thinking consolidated skills had been pruned.
from __future__ import annotations
import json
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
import pytest
@@ -84,7 +84,7 @@ def test_classify_consolidated_via_write_file_evidence(curator_env):
def test_report_md_splits_consolidated_and_pruned_sections(curator_env):
"""End-to-end: REPORT.md shows both sections distinctly."""
curator = curator_env
- start = datetime.now(timezone.utc)
+ start = datetime.now(UTC)
before = [
{"name": "absorbed-skill", "state": "active", "pinned": False},
@@ -209,7 +209,7 @@ def test_reconcile_model_block_visible_in_full_report(curator_env):
import json as _json
from datetime import datetime as _dt, timezone as _tz
- start = _dt.now(_tz.utc)
+ start = _dt.now(UTC)
before = [
{"name": "anthropic-api", "state": "active", "pinned": False},
{"name": "stale-thing", "state": "stale", "pinned": False},
diff --git a/tests/agent/test_curator_reports.py b/tests/agent/test_curator_reports.py
index 721dae348cb..ff69f71452b 100644
--- a/tests/agent/test_curator_reports.py
+++ b/tests/agent/test_curator_reports.py
@@ -7,7 +7,7 @@ the standard log dir, not inside the user's ``skills/`` data directory.
from __future__ import annotations
import json
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
import pytest
@@ -51,7 +51,7 @@ def _make_llm_meta(**overrides):
def test_write_run_report_creates_both_files(curator_env):
"""Each run writes both a run.json (machine) and a REPORT.md (human)."""
curator = curator_env["curator"]
- start = datetime.now(timezone.utc)
+ start = datetime.now(UTC)
run_dir = curator._write_run_report(
started_at=start,
@@ -80,7 +80,7 @@ def test_same_second_reruns_get_unique_dirs(curator_env):
"""If the curator somehow runs twice in the same second, the second
report still gets its own directory rather than overwriting the first."""
curator = curator_env["curator"]
- start = datetime(2026, 4, 29, 5, 33, 34, tzinfo=timezone.utc)
+ start = datetime(2026, 4, 29, 5, 33, 34, tzinfo=UTC)
kwargs = dict(
started_at=start,
@@ -155,7 +155,7 @@ def test_curator_rewrites_cron_skills_when_skill_consolidated(curator_env_with_c
after = [{"name": "foo-umbrella", "state": "active", "pinned": False}]
run_dir = curator._write_run_report(
- started_at=datetime.now(timezone.utc),
+ started_at=datetime.now(UTC),
elapsed_seconds=3.0,
auto_counts={"checked": 1, "marked_stale": 0, "archived": 0, "reactivated": 0},
auto_summary="no changes",
diff --git a/tests/agent/test_rate_limit_reset_hint.py b/tests/agent/test_rate_limit_reset_hint.py
index 94253a7b7e5..4a2ef3deb45 100644
--- a/tests/agent/test_rate_limit_reset_hint.py
+++ b/tests/agent/test_rate_limit_reset_hint.py
@@ -14,6 +14,7 @@ import pytest
from agent.agent_runtime_helpers import extract_api_error_context
from agent.turn_recovery import compute_error_backoff, reset_hint
+from datetime import UTC
def _codex_429(**fields):
@@ -81,7 +82,7 @@ def test_live_wait_line_names_the_reset_window_too():
def test_vendor_reset_headers_feed_reset_at(headers, expected_seconds):
from datetime import datetime, timedelta, timezone
if "anthropic-ratelimit-requests-reset" in headers:
- when = datetime.now(timezone.utc) + timedelta(seconds=900)
+ when = datetime.now(UTC) + timedelta(seconds=900)
headers["anthropic-ratelimit-requests-reset"] = when.strftime("%Y-%m-%dT%H:%M:%SZ")
err = Exception("HTTP 429: rate limit")
err.response = MagicMock(headers=headers)
diff --git a/tests/agent/test_retry_delay_parsers_shared.py b/tests/agent/test_retry_delay_parsers_shared.py
index a414821a80e..d3ea34d3691 100644
--- a/tests/agent/test_retry_delay_parsers_shared.py
+++ b/tests/agent/test_retry_delay_parsers_shared.py
@@ -4,7 +4,7 @@ Cluster: every consumer of ``Retry-After`` / free-text reset grammars goes throu
so an HTTP-date header or a "resets in 2 hours 5 minutes" body yields the same wait everywhere.
"""
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from email.utils import format_datetime
from types import SimpleNamespace
@@ -14,7 +14,7 @@ from agent.retry_utils import parse_retry_after_seconds, reset_delay_from_messag
def _http_date(seconds_ahead: int) -> str:
- return format_datetime(datetime.now(timezone.utc) + timedelta(seconds=seconds_ahead), usegmt=True)
+ return format_datetime(datetime.now(UTC) + timedelta(seconds=seconds_ahead), usegmt=True)
class TestRetryAfterHeaderOneParser:
diff --git a/tests/agent/test_retry_utils.py b/tests/agent/test_retry_utils.py
index 2b957725b43..e090364669e 100644
--- a/tests/agent/test_retry_utils.py
+++ b/tests/agent/test_retry_utils.py
@@ -6,6 +6,7 @@ from agent import retry_utils
from types import SimpleNamespace
from agent.retry_utils import adaptive_rate_limit_backoff, jittered_backoff
+from datetime import UTC
def test_backoff_is_exponential():
@@ -147,11 +148,11 @@ class TestParseRetryAfterSeconds:
from email.utils import format_datetime
from agent.retry_utils import parse_retry_after_seconds
- future = datetime.now(timezone.utc) + timedelta(seconds=90)
+ future = datetime.now(UTC) + timedelta(seconds=90)
seconds = parse_retry_after_seconds(format_datetime(future, usegmt=True))
assert seconds is not None and 80 <= seconds <= 91
- past = datetime.now(timezone.utc) - timedelta(seconds=90)
+ past = datetime.now(UTC) - timedelta(seconds=90)
assert parse_retry_after_seconds(format_datetime(past, usegmt=True)) == 0.0
diff --git a/tests/agent/test_ssl_transport_contracts.py b/tests/agent/test_ssl_transport_contracts.py
index d8bac8372a8..3dd28a28b10 100644
--- a/tests/agent/test_ssl_transport_contracts.py
+++ b/tests/agent/test_ssl_transport_contracts.py
@@ -1,7 +1,7 @@
"""TLS assertions reach real client transports, never the host certificate store."""
from __future__ import annotations
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from ipaddress import ip_address
import ssl
@@ -22,7 +22,7 @@ from agent import model_metadata, process_bootstrap, ssl_verify
def local_tls(tmp_path, monkeypatch):
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "test loopback")])
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name)
.public_key(key.public_key()).serial_number(x509.random_serial_number())
.not_valid_before(now - timedelta(days=1)).not_valid_after(now + timedelta(days=1))
diff --git a/tests/agent/test_ssl_verify.py b/tests/agent/test_ssl_verify.py
index a69d65ccb29..0079c88f986 100644
--- a/tests/agent/test_ssl_verify.py
+++ b/tests/agent/test_ssl_verify.py
@@ -9,6 +9,7 @@ from pathlib import Path
import pytest
from agent.ssl_verify import resolve_httpx_verify
+from datetime import UTC
@pytest.fixture
@@ -107,7 +108,7 @@ def test_explicit_provider_ca_replaces_platform_trust_on_real_https(tmp_path):
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "Private provider")])
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
cert = (x509.CertificateBuilder().subject_name(subject).issuer_name(subject)
.public_key(key.public_key()).serial_number(x509.random_serial_number())
.not_valid_before(now - timedelta(days=1)).not_valid_after(now + timedelta(days=1))
diff --git a/tests/agent/test_verification_evidence.py b/tests/agent/test_verification_evidence.py
index 3401e913f46..9131dc6f775 100644
--- a/tests/agent/test_verification_evidence.py
+++ b/tests/agent/test_verification_evidence.py
@@ -1,7 +1,7 @@
import json
import sqlite3
import tempfile
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
import pytest
@@ -414,7 +414,7 @@ def test_recording_expires_old_edit_only_state(tmp_path, monkeypatch):
cwd=tmp_path,
paths=[str(tmp_path / "src" / "app.ts")],
)
- cutoff = (datetime.now(timezone.utc) - timedelta(days=31)).isoformat()
+ cutoff = (datetime.now(UTC) - timedelta(days=31)).isoformat()
with sqlite3.connect(home / "verification_evidence.db") as conn:
conn.execute("UPDATE verification_state SET last_edit_at = ?", (cutoff,))
conn.commit()
diff --git a/tests/ci/test_timings_report.py b/tests/ci/test_timings_report.py
index 723565aaf8e..b13a0fe8e39 100644
--- a/tests/ci/test_timings_report.py
+++ b/tests/ci/test_timings_report.py
@@ -9,7 +9,7 @@ and provides a one-line summary plus optional per-job delta detail.
from __future__ import annotations
import importlib.util
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
_PATH = Path(__file__).resolve().parents[2] / "scripts" / "ci" / "timings_report.py"
@@ -19,13 +19,13 @@ if _spec is None or _spec.loader is None:
_mod = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_mod)
-_T0 = datetime(2025, 1, 1, 0, 0, 0, tzinfo=timezone.utc)
+_T0 = datetime(2025, 1, 1, 0, 0, 0, tzinfo=UTC)
def _ts(seconds: float) -> str:
"""ISO timestamp `seconds` after T0."""
dt = _T0.timestamp() + seconds
- return datetime.fromtimestamp(dt, tz=timezone.utc).isoformat().replace("+00:00", "Z")
+ return datetime.fromtimestamp(dt, tz=UTC).isoformat().replace("+00:00", "Z")
def _job(name: str, dur_s: float, start_s: float = 0.0, conclusion: str = "success") -> dict:
diff --git a/tests/cron/test_claim_job_for_fire.py b/tests/cron/test_claim_job_for_fire.py
index a7961df9f07..d4bf696eb92 100644
--- a/tests/cron/test_claim_job_for_fire.py
+++ b/tests/cron/test_claim_job_for_fire.py
@@ -11,6 +11,7 @@ import threading
import time
import pytest
+from datetime import UTC
@pytest.fixture
@@ -323,7 +324,7 @@ def test_claim_seconds_before_the_slot_owns_it_once(temp_home, monkeypatch):
executions.finish_execution(row["id"], success=True)
jobs.mark_job_run(job["id"], True)
- backstop = slot_dt.astimezone(timezone.utc) + timedelta(minutes=11)
+ backstop = slot_dt.astimezone(UTC) + timedelta(minutes=11)
monkeypatch.setattr(jobs, "_hermes_now", lambda: backstop)
monkeypatch.setattr(executions, "_hermes_now", lambda: backstop)
assert jobs.claim_job_for_fire(job["id"], return_job=True) is False, (
diff --git a/tests/cron/test_cron_script.py b/tests/cron/test_cron_script.py
index 87ab61e8d0f..76456f93b48 100644
--- a/tests/cron/test_cron_script.py
+++ b/tests/cron/test_cron_script.py
@@ -13,7 +13,7 @@ import re
import subprocess
import sys
import textwrap
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
from types import SimpleNamespace
from typing import cast
@@ -74,7 +74,7 @@ class TestJobScriptField:
def test_cronjob_tool_rejects_stale_past_one_shot(cron_env, monkeypatch):
from tools.cronjob_tools import cronjob
- now = datetime(2026, 3, 18, 4, 30, 0, tzinfo=timezone.utc)
+ now = datetime(2026, 3, 18, 4, 30, 0, tzinfo=UTC)
monkeypatch.setattr("cron.jobs._hermes_now", lambda: now)
stale = (now - timedelta(minutes=5)).isoformat()
diff --git a/tests/cron/test_dispatch_lateness_stamp.py b/tests/cron/test_dispatch_lateness_stamp.py
index adbfe1edc1d..cba7122682a 100644
--- a/tests/cron/test_dispatch_lateness_stamp.py
+++ b/tests/cron/test_dispatch_lateness_stamp.py
@@ -8,7 +8,7 @@ kind) on every recurring dispatch so `hermes cron list` and
`hermes cron status` can surface late catch-ups.
"""
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
import pytest
@@ -19,7 +19,7 @@ from cron.jobs import (
save_jobs,
)
-FIXED_NOW = datetime(2026, 9, 1, 9, 31, 0, tzinfo=timezone.utc)
+FIXED_NOW = datetime(2026, 9, 1, 9, 31, 0, tzinfo=UTC)
@pytest.fixture()
diff --git a/tests/cron/test_due_scan_dst_fold.py b/tests/cron/test_due_scan_dst_fold.py
index 0b57069393f..ce51505edb9 100644
--- a/tests/cron/test_due_scan_dst_fold.py
+++ b/tests/cron/test_due_scan_dst_fold.py
@@ -1,6 +1,6 @@
"""Due-scan comparisons must use absolute instants across a repeated DST hour."""
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from zoneinfo import ZoneInfo
import hermes_time
@@ -25,7 +25,7 @@ def dst_cron_store(tmp_path, monkeypatch):
def _instant(hour, minute):
- return datetime(2026, 11, 1, hour, minute, tzinfo=timezone.utc).astimezone(NEW_YORK)
+ return datetime(2026, 11, 1, hour, minute, tzinfo=UTC).astimezone(NEW_YORK)
def _job(next_run_at):
diff --git a/tests/cron/test_due_scan_save_failure.py b/tests/cron/test_due_scan_save_failure.py
index 69e9203cb41..a165c6d48f7 100644
--- a/tests/cron/test_due_scan_save_failure.py
+++ b/tests/cron/test_due_scan_save_failure.py
@@ -23,13 +23,13 @@ import sqlite3
from datetime import timedelta
import pytest
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from cron import jobs as cronjobs
from cron import store_health
from cron.jobs import get_due_jobs, load_jobs, save_jobs
-FIXED_NOW = datetime(2026, 6, 22, 12, 0, 0, tzinfo=timezone.utc)
+FIXED_NOW = datetime(2026, 6, 22, 12, 0, 0, tzinfo=UTC)
@pytest.fixture()
diff --git a/tests/cron/test_duration_dst.py b/tests/cron/test_duration_dst.py
index 1ba4e22b2ab..7da881df7a4 100644
--- a/tests/cron/test_duration_dst.py
+++ b/tests/cron/test_duration_dst.py
@@ -1,6 +1,6 @@
"""Duration schedules measure elapsed time, including across UTC offset changes."""
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from zoneinfo import ZoneInfo
import pytest
@@ -27,7 +27,7 @@ def test_one_shot_delay_preserves_elapsed_duration(monkeypatch, start):
schedule = jobs.parse_schedule("in 2h")
run_at = datetime.fromisoformat(schedule["run_at"])
- assert run_at.astimezone(timezone.utc) - start.astimezone(timezone.utc) == timedelta(hours=2)
+ assert run_at.astimezone(UTC) - start.astimezone(UTC) == timedelta(hours=2)
assert run_at.utcoffset() == run_at.astimezone(start.tzinfo).utcoffset()
@@ -41,5 +41,5 @@ def test_interval_preserves_elapsed_duration(monkeypatch, start, resume):
schedule, last_run_at=start.isoformat() if resume else None,
))
- assert run_at.astimezone(timezone.utc) - start.astimezone(timezone.utc) == timedelta(hours=2)
+ assert run_at.astimezone(UTC) - start.astimezone(UTC) == timedelta(hours=2)
assert run_at.utcoffset() == run_at.astimezone(start.tzinfo).utcoffset()
diff --git a/tests/cron/test_inflight_stale_guard.py b/tests/cron/test_inflight_stale_guard.py
index c83c275e81e..d106409a9db 100644
--- a/tests/cron/test_inflight_stale_guard.py
+++ b/tests/cron/test_inflight_stale_guard.py
@@ -38,7 +38,7 @@ Design notes
"""
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from unittest.mock import patch
import pytest
@@ -370,7 +370,7 @@ class TestLedgerTerminalReconciliation:
def _row_at(offset_seconds: float) -> str:
"""ISO claimed_at at now+offset (aware, local tz)."""
return datetime.fromtimestamp(
- time.time() + offset_seconds, tz=timezone.utc
+ time.time() + offset_seconds, tz=UTC
).isoformat()
def _inject_young_claim(self, job_id: str, home) -> None:
diff --git a/tests/cron/test_jobs.py b/tests/cron/test_jobs.py
index 476ba161f42..8120020087e 100644
--- a/tests/cron/test_jobs.py
+++ b/tests/cron/test_jobs.py
@@ -2,7 +2,7 @@
import threading
import pytest
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from cron.jobs import (
parse_duration,
@@ -303,7 +303,7 @@ class TestComputeNextRun:
assert compute_next_run(schedule) == future
def test_once_recent_past_within_grace_returns_time(self, monkeypatch):
- now = datetime(2026, 3, 18, 4, 22, 3, tzinfo=timezone.utc)
+ now = datetime(2026, 3, 18, 4, 22, 3, tzinfo=UTC)
run_at = "2026-03-18T04:22:00+00:00"
monkeypatch.setattr("cron.jobs._hermes_now", lambda: now)
@@ -313,7 +313,7 @@ class TestComputeNextRun:
def test_once_with_last_run_returns_none_even_within_grace(self, monkeypatch):
- now = datetime(2026, 3, 18, 4, 22, 3, tzinfo=timezone.utc)
+ now = datetime(2026, 3, 18, 4, 22, 3, tzinfo=UTC)
run_at = "2026-03-18T04:22:00+00:00"
monkeypatch.setattr("cron.jobs._hermes_now", lambda: now)
@@ -497,7 +497,7 @@ class TestJobCRUD:
assert updated["repeat"]["times"] == 1
def test_rejects_stale_past_one_shot_at_creation(self, tmp_cron_dir, monkeypatch):
- now = datetime(2026, 3, 18, 4, 30, 0, tzinfo=timezone.utc)
+ now = datetime(2026, 3, 18, 4, 30, 0, tzinfo=UTC)
monkeypatch.setattr("cron.jobs._hermes_now", lambda: now)
stale = (now - timedelta(minutes=5)).isoformat()
@@ -623,7 +623,7 @@ class TestPauseResumeJob:
def test_resume_rejects_past_oneshot(self, tmp_cron_dir, monkeypatch):
"""Resuming a paused one-shot whose time is now in the past must raise
ValueError — the revived job would silently never fire."""
- now = datetime(2026, 7, 6, 12, 0, 0, tzinfo=timezone.utc)
+ now = datetime(2026, 7, 6, 12, 0, 0, tzinfo=UTC)
monkeypatch.setattr("cron.jobs._hermes_now", lambda: now)
# Create directly — bypass create_job's past-oneshot guard so we can
# test the resume path independently.
@@ -653,12 +653,12 @@ class TestPauseResumeJob:
"""A recurring job paused before its slot and resumed after it comes back with that slot
still due — the due scan then fires it (late/catch-up) or logs the skip. Re-anchoring
from now consumed the occurrence with no run, no ledger row and no log line (#113603)."""
- now = datetime(2026, 9, 16, 17, 0, 0, tzinfo=timezone.utc)
+ now = datetime(2026, 9, 16, 17, 0, 0, tzinfo=UTC)
monkeypatch.setattr("cron.jobs._hermes_now", lambda: now)
job = create_job(prompt="daily pipeline", schedule="30 1 * * *", deliver="local")
stored = load_jobs()
row = next(r for r in stored if r["id"] == job["id"])
- slot = datetime(2026, 9, 16, 1, 30, 0, tzinfo=timezone.utc).isoformat()
+ slot = datetime(2026, 9, 16, 1, 30, 0, tzinfo=UTC).isoformat()
row["next_run_at"] = slot
save_jobs(stored)
@@ -672,7 +672,7 @@ class TestPauseResumeJob:
def test_resume_recomputes_future_or_missing_slot_from_now(self, tmp_cron_dir, monkeypatch):
"""Control: a paused job whose stored slot is still ahead, or created ``--paused`` with no
slot, resumes onto the next future occurrence as before."""
- now = datetime(2026, 9, 16, 17, 0, 0, tzinfo=timezone.utc)
+ now = datetime(2026, 9, 16, 17, 0, 0, tzinfo=UTC)
monkeypatch.setattr("cron.jobs._hermes_now", lambda: now)
ahead = create_job(prompt="daily", schedule="30 1 * * *", deliver="local")
pause_job(ahead["id"])
@@ -1086,7 +1086,7 @@ class TestGetDueJobs:
def test_broken_recent_one_shot_without_next_run_is_recovered(self, tmp_cron_dir, monkeypatch):
- now = datetime(2026, 3, 18, 4, 22, 30, tzinfo=timezone.utc)
+ now = datetime(2026, 3, 18, 4, 22, 30, tzinfo=UTC)
monkeypatch.setattr("cron.jobs._hermes_now", lambda: now)
run_at = "2026-03-18T04:22:00+00:00"
@@ -1205,8 +1205,8 @@ class TestGetDueJobs:
def test_heartbeat_run_claim_rejects_replaced_owner(self, tmp_cron_dir):
"""A resumed stale runner must not keep a newer owner's claim alive."""
- future = (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat()
- original_at = datetime.now(timezone.utc).isoformat()
+ future = (datetime.now(UTC) + timedelta(hours=1)).isoformat()
+ original_at = datetime.now(UTC).isoformat()
save_jobs([{
"id": "reclaimed", "name": "R", "prompt": "x",
"schedule": {"kind": "once", "run_at": future},
@@ -1297,7 +1297,7 @@ class TestBadNextRunAtRecovery:
must be repaired (next_run_at cleared so recovery can set a sane value).
"""
from datetime import timezone, timedelta as td
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
past = (now - td(seconds=30)).isoformat()
future = (now + td(days=1)).isoformat()
@@ -1353,7 +1353,7 @@ class TestPerJobScanContainment:
from datetime import timezone, timedelta as td
from unittest.mock import patch as mock_patch
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
past = (now - td(seconds=30)).isoformat()
poison = {
@@ -1472,7 +1472,7 @@ class TestClaimDispatch:
# A claimed one-shot whose tick died leaves completed>=times with
# last_run_at still unset, so the recovery helper re-arms it as due.
# get_due_jobs must drop it instead of returning it for another fire.
- past = (datetime.now(timezone.utc) - timedelta(seconds=5)).isoformat()
+ past = (datetime.now(UTC) - timedelta(seconds=5)).isoformat()
save_jobs([{
"id": "os1",
"name": "one-shot",
@@ -1907,7 +1907,7 @@ class TestCompletedOneshotRetentionSweep:
job = create_job(prompt="Once", schedule="in 30m", repeat=1)
mark_job_run(job["id"], success=True, delivery_error="boom")
stamp = (
- datetime.now(timezone.utc) - timedelta(days=age_days)
+ datetime.now(UTC) - timedelta(days=age_days)
).isoformat()
jobs = load_jobs()
for j in jobs:
@@ -1933,7 +1933,7 @@ class TestCompletedOneshotRetentionSweep:
"""Old recurring jobs are never candidates, whatever their history."""
job = create_job(prompt="Recurring", schedule="every 1h")
stamp = (
- datetime.now(timezone.utc) - timedelta(days=365)
+ datetime.now(UTC) - timedelta(days=365)
).isoformat()
jobs = load_jobs()
for j in jobs:
diff --git a/tests/cron/test_oneshot_grace_due_scan.py b/tests/cron/test_oneshot_grace_due_scan.py
index f6bb6e676fe..92b3bc1e234 100644
--- a/tests/cron/test_oneshot_grace_due_scan.py
+++ b/tests/cron/test_oneshot_grace_due_scan.py
@@ -17,7 +17,7 @@ These tests pin the due-scan grace gate:
"""
import pytest
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from cron.jobs import (
get_due_jobs,
@@ -26,7 +26,7 @@ from cron.jobs import (
trigger_job,
)
-FIXED_NOW = datetime(2026, 6, 22, 12, 0, 0, tzinfo=timezone.utc)
+FIXED_NOW = datetime(2026, 6, 22, 12, 0, 0, tzinfo=UTC)
@pytest.fixture()
diff --git a/tests/cron/test_persisted_error_rearm_legality.py b/tests/cron/test_persisted_error_rearm_legality.py
index 74370df3ce8..4d2fe01e4d3 100644
--- a/tests/cron/test_persisted_error_rearm_legality.py
+++ b/tests/cron/test_persisted_error_rearm_legality.py
@@ -9,7 +9,7 @@ still re-arm to now — an immediate catch-up is always legal for intervals.
from __future__ import annotations
import sys
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
from unittest import mock
@@ -55,19 +55,19 @@ class TestCronRearmRespectsScheduleLegality:
Monday 9am (the next legal occurrence), NOT to Saturday-now."""
job = J.create_job(prompt="weekday report", schedule="0 9 * * 1-5")
# Saturday 2026-08-22 12:00 UTC; Friday's run errored at 9am.
- now = datetime(2026, 8, 22, 12, 0, tzinfo=timezone.utc)
+ now = datetime(2026, 8, 22, 12, 0, tzinfo=UTC)
_wedge(
job["id"],
# parked well past Monday (the wedge shape: stale error + future park)
- next_run_at=datetime(2026, 8, 26, 9, 0, tzinfo=timezone.utc),
- last_run_at=datetime(2026, 8, 21, 9, 0, tzinfo=timezone.utc),
+ next_run_at=datetime(2026, 8, 26, 9, 0, tzinfo=UTC),
+ last_run_at=datetime(2026, 8, 21, 9, 0, tzinfo=UTC),
)
with mock.patch.object(J, "_hermes_now", lambda: now):
due = J.get_due_jobs()
assert due == [], "Saturday must not fire a weekday-only job"
rearmed = J.get_job(job["id"])
next_dt = datetime.fromisoformat(rearmed["next_run_at"])
- assert next_dt == datetime(2026, 8, 24, 9, 0, tzinfo=timezone.utc), (
+ assert next_dt == datetime(2026, 8, 24, 9, 0, tzinfo=UTC), (
f"expected re-arm to Monday 9am, got {rearmed['next_run_at']}"
)
# The recovery is still counted (the wedge WAS repaired).
@@ -77,8 +77,8 @@ class TestCronRearmRespectsScheduleLegality:
"""A wedged-looking job whose next_run_at already IS the next legal
occurrence needs no repair — re-arm must be a no-op."""
job = J.create_job(prompt="daily", schedule="30 14 * * *")
- now = datetime(2026, 8, 22, 12, 0, tzinfo=timezone.utc)
- legal_next = datetime(2026, 8, 22, 14, 30, tzinfo=timezone.utc)
+ now = datetime(2026, 8, 22, 12, 0, tzinfo=UTC)
+ legal_next = datetime(2026, 8, 22, 14, 30, tzinfo=UTC)
_wedge(
job["id"],
next_run_at=legal_next,
@@ -93,7 +93,7 @@ class TestCronRearmRespectsScheduleLegality:
"""Interval jobs (the 2026-08-14 incident class) keep the immediate
catch-up: re-armed to now, due on this same scan."""
job = J.create_job(prompt="probe", schedule="every 10m", no_agent=True, script="p.py")
- now = datetime(2026, 8, 22, 12, 0, tzinfo=timezone.utc)
+ now = datetime(2026, 8, 22, 12, 0, tzinfo=UTC)
_wedge(
job["id"],
next_run_at=now + timedelta(minutes=5),
diff --git a/tests/cron/test_quota_hold.py b/tests/cron/test_quota_hold.py
index 9eed562ba12..4307fbc0203 100644
--- a/tests/cron/test_quota_hold.py
+++ b/tests/cron/test_quota_hold.py
@@ -8,7 +8,7 @@ model clears the marker. The hint is read only from the AuthError in the cause c
arbitrary failure text.
"""
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from unittest.mock import MagicMock, patch
import pytest
@@ -57,8 +57,8 @@ def test_weekly_cron_retries_when_quota_recovers_before_next_occurrence(
):
"""A weekly fire blocked by a shorter quota window retries when the provider reopens;
it is not silently deferred until the following week's natural occurrence."""
- now = datetime(2026, 9, 18, 12, 1, tzinfo=timezone.utc)
- natural_next = datetime(2026, 9, 25, 12, 0, tzinfo=timezone.utc)
+ now = datetime(2026, 9, 18, 12, 1, tzinfo=UTC)
+ natural_next = datetime(2026, 9, 25, 12, 0, tzinfo=UTC)
monkeypatch.setattr("cron.jobs._hermes_now", lambda: now)
monkeypatch.setattr(qh, "_hermes_now", lambda: now)
job = create_job("weekly digest", "0 12 * * 5")
@@ -85,12 +85,12 @@ def test_recovery_fire_skips_dense_schedules_and_never_re_parks(monkeypatch):
"""Recovery is one attempt for sparse schedules only: an hourly job whose hold ends two
minutes before :00 keeps its natural :00 (no off-lattice near-duplicate), and a job that is
already the recovery fire (carries quota_hold_until) failing again is not re-parked."""
- now = datetime(2026, 9, 18, 12, 1, tzinfo=timezone.utc)
+ now = datetime(2026, 9, 18, 12, 1, tzinfo=UTC)
monkeypatch.setattr(qh, "_hermes_now", lambda: now)
dense = {
"schedule": {"kind": "cron", "expr": "0 * * * *"},
- "next_run_at": datetime(2026, 9, 18, 13, 0, tzinfo=timezone.utc).isoformat(),
+ "next_run_at": datetime(2026, 9, 18, 13, 0, tzinfo=UTC).isoformat(),
}
natural = dense["next_run_at"]
assert not qh.plan_hold(dense, hold_seconds=57 * 60 - qh.HOLD_SLACK_SECONDS,
@@ -138,7 +138,7 @@ def test_quota_hold_parks_past_window_survives_stale_rearm_and_clears_on_model_r
cadence+grace). The marker clears once a run reaches the model."""
job = create_job("portfolio triage", "every 30m", deliver="local")
job_id = job["id"]
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
deliveries: list = []
_tick(get_job(job_id), tmp_cron_home, deliveries, _raise_quota)
diff --git a/tests/cron/test_recurring_persisted_error_recovery.py b/tests/cron/test_recurring_persisted_error_recovery.py
index 3a89ba48e63..83412ac305c 100644
--- a/tests/cron/test_recurring_persisted_error_recovery.py
+++ b/tests/cron/test_recurring_persisted_error_recovery.py
@@ -29,7 +29,7 @@ execution row, no re-dispatch); with the recovery it re-fires and completes.
from __future__ import annotations
import sys
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
from unittest import mock
@@ -79,7 +79,7 @@ def _setup(cron_env, monkeypatch):
def _persist_stale_error(J, job_id, *, error_age_minutes=110):
"""Persist the incident wedge state: last_status=error, last_run stale by
more than a full cadence, next_run_at re-armed into the future."""
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
J.update_job(
job_id,
{
@@ -147,7 +147,7 @@ class TestPersistedStaleErrorRecovery:
job_id = env["job_id"]
_persist_stale_error(J, job_id, error_age_minutes=110)
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
J.update_job(
job_id,
{"fire_claim": {"at": now.isoformat(), "by": "other-host:deadbeef"}},
diff --git a/tests/cron/test_recurring_wedge_selfheal.py b/tests/cron/test_recurring_wedge_selfheal.py
index ee29873c33e..137a3cefa0f 100644
--- a/tests/cron/test_recurring_wedge_selfheal.py
+++ b/tests/cron/test_recurring_wedge_selfheal.py
@@ -29,7 +29,7 @@ from __future__ import annotations
import sys
import time
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
from unittest import mock
@@ -60,7 +60,7 @@ def cron_env(tmp_path, monkeypatch):
no_agent=True,
script="probe.py",
)
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
jobs_mod.update_job(job["id"], {"next_run_at": (now - timedelta(minutes=1)).isoformat()})
script = hermes_home / "scripts" / "probe.py"
@@ -165,7 +165,7 @@ class TestEAGAINCreateExecutionLeak:
assert job_id not in S.get_running_job_ids()
# Second tick (substrate recovered): job re-dispatches and completes.
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
J.update_job(job_id, {"next_run_at": (now - timedelta(minutes=1)).isoformat()})
with mock.patch("cron.jobs.load_jobs", return_value=[J.get_job(job_id)]):
S.tick(verbose=False, sync=True)
diff --git a/tests/cron/test_retirement_dispatch.py b/tests/cron/test_retirement_dispatch.py
index 7f3d2512556..42523d584fc 100644
--- a/tests/cron/test_retirement_dispatch.py
+++ b/tests/cron/test_retirement_dispatch.py
@@ -1,7 +1,7 @@
"""The tick-to-worker handoff must have no retirement-sized gap after can_dispatch."""
from concurrent.futures import ThreadPoolExecutor
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
import threading
@@ -13,7 +13,7 @@ def test_passed_gate_tick_and_queued_job_remain_busy_until_real_worker_exit(tmp_
monkeypatch.setattr(backend_retirement, "retirement", fence)
script = tmp_path / "job.py"
script.write_text("print('no model')\n")
- job = jobs.create_job(prompt=None, schedule=datetime.now(timezone.utc).isoformat(), script=str(script), no_agent=True)
+ job = jobs.create_job(prompt=None, schedule=datetime.now(UTC).isoformat(), script=str(script), no_agent=True)
for name in ("_maybe_run_worktree_maintenance", "_sweep_mcp_orphans", "_maybe_reap_dead_owners"):
monkeypatch.setattr(scheduler, name, lambda: None)
monkeypatch.setattr(scheduler, "_should_yield_tick_to_fresh_gateway", lambda: None)
diff --git a/tests/cron/test_scheduled_occurrence.py b/tests/cron/test_scheduled_occurrence.py
index 0de70a3a539..c350b46f5d4 100644
--- a/tests/cron/test_scheduled_occurrence.py
+++ b/tests/cron/test_scheduled_occurrence.py
@@ -6,6 +6,7 @@ import subprocess
import sys
import pytest
+from datetime import UTC
_FIRE = """
@@ -167,13 +168,13 @@ def test_completion_before_occurrence_does_not_prove_slot_completed(tmp_path, mo
monkeypatch.setattr(executions, 'EXECUTIONS_FILE', tmp_path / 'executions.db')
slot = '2026-01-05T00:00:00+00:00'
- monkeypatch.setattr(executions, '_hermes_now', lambda: datetime(2026, 1, 1, tzinfo=timezone.utc))
+ monkeypatch.setattr(executions, '_hermes_now', lambda: datetime(2026, 1, 1, tzinfo=UTC))
poisoned = executions.create_execution('job', source='control', scheduled_instant=slot)
executions.finish_execution(poisoned['id'], success=True)
assert not completed_occurrence({'id': 'job'}, slot)
- monkeypatch.setattr(executions, '_hermes_now', lambda: datetime(2026, 1, 5, tzinfo=timezone.utc))
+ monkeypatch.setattr(executions, '_hermes_now', lambda: datetime(2026, 1, 5, tzinfo=UTC))
legitimate = executions.create_execution('job', source='builtin', scheduled_instant=slot)
executions.finish_execution(legitimate['id'], success=True)
diff --git a/tests/cron/test_terminal_job_rearm.py b/tests/cron/test_terminal_job_rearm.py
index d6e84a39c3f..f8f6de9b63f 100644
--- a/tests/cron/test_terminal_job_rearm.py
+++ b/tests/cron/test_terminal_job_rearm.py
@@ -1,6 +1,6 @@
"""Behavioral coverage for terminal cron jobs and explicit one-shot re-arm."""
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
import copy
from unittest import mock
@@ -52,7 +52,7 @@ def test_exhausted_recurring_job_trigger_is_refused(tmp_cron_dir):
def test_wedged_claimed_oneshot_remains_triggerable(tmp_cron_dir):
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
job = create_job("wedged", "in 30m", repeat=2)
record = get_job(job["id"])
record.update({
@@ -104,7 +104,7 @@ def test_rearm_completed_oneshot_restores_schedule_and_preserves_history(tmp_cro
job = create_job("done", "in 30m", repeat=3)
mark_job_run(job["id"], success=True)
finished = get_job(job["id"])
- run_at = (datetime.now(timezone.utc) + timedelta(minutes=5)).isoformat()
+ run_at = (datetime.now(UTC) + timedelta(minutes=5)).isoformat()
rearmed = rearm_oneshot(job["id"], run_at)
assert rearmed["schedule"]["kind"] == "once"
@@ -120,13 +120,13 @@ def test_rearm_completed_oneshot_restores_schedule_and_preserves_history(tmp_cro
def test_rearm_refuses_recurring_and_live_claim(tmp_cron_dir):
recurring = create_job("recurring", "every 1h")
- future = (datetime.now(timezone.utc) + timedelta(minutes=5)).isoformat()
+ future = (datetime.now(UTC) + timedelta(minutes=5)).isoformat()
with pytest.raises(ValueError, match="one-shot"):
rearm_oneshot(recurring["id"], future)
oneshot = create_job("claimed", "in 30m")
record = get_job(oneshot["id"])
- record["run_claim"] = {"at": datetime.now(timezone.utc).isoformat(), "by": "live"}
+ record["run_claim"] = {"at": datetime.now(UTC).isoformat(), "by": "live"}
save_jobs([record])
with pytest.raises(ValueError, match="claim"):
rearm_oneshot(oneshot["id"], future)
diff --git a/tests/cron/test_timezone.py b/tests/cron/test_timezone.py
index e2cafba2dba..12aee21d352 100644
--- a/tests/cron/test_timezone.py
+++ b/tests/cron/test_timezone.py
@@ -12,7 +12,7 @@ Covers:
import os
import sys
import pytest
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from unittest.mock import patch
import hermes_time
@@ -300,8 +300,8 @@ class TestCronTimezone:
# The UTC equivalent must match what we'd get by correctly interpreting
# the naive dt as system-local time first, then converting
system_tz = datetime.now().astimezone().tzinfo
- expected_utc = naive_dt.replace(tzinfo=system_tz).astimezone(timezone.utc)
- actual_utc = result.astimezone(timezone.utc)
+ expected_utc = naive_dt.replace(tzinfo=system_tz).astimezone(UTC)
+ actual_utc = result.astimezone(UTC)
assert actual_utc == expected_utc, (
f"Absolute time shifted: expected {expected_utc}, got {actual_utc}"
)
diff --git a/tests/cron/test_unreachable_retry.py b/tests/cron/test_unreachable_retry.py
index 17cff91cd63..1891aad806d 100644
--- a/tests/cron/test_unreachable_retry.py
+++ b/tests/cron/test_unreachable_retry.py
@@ -6,7 +6,7 @@ bounded ladder (5/15/30 min); a run that reaches the model resets the ladder, an
ladder never fires past its last rung.
"""
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
import pytest
@@ -40,7 +40,7 @@ def test_unreachable_failure_pulls_next_run_earlier_then_ladder_exhausts(
job = create_job("nightly report", "every 24h")
job_id = job["id"]
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
for i, delay in enumerate(ur.RETRY_DELAYS_SECONDS):
assert mark_job_run(job_id, False, "ConnectError: dns", model_unreachable=True)
j = get_job(job_id)
@@ -56,7 +56,7 @@ def test_unreachable_failure_pulls_next_run_earlier_then_ladder_exhausts(
assert j.get(ur.STATE_KEY) is None
assert datetime.fromisoformat(j["next_run_at"]) - now > timedelta(hours=1)
- pinned = datetime(2026, 9, 18, 12, 1, tzinfo=timezone.utc)
+ pinned = datetime(2026, 9, 18, 12, 1, tzinfo=UTC)
monkeypatch.setattr("cron.jobs._hermes_now", lambda: pinned)
monkeypatch.setattr(ur, "_hermes_now", lambda: pinned)
weekly = create_job("weekly digest", "0 12 * * 5")
@@ -119,11 +119,11 @@ def test_reaching_the_model_resets_ladder_and_oneshots_never_retry(tmp_cron_home
assert mark_job_run(job_id, False, "agent error")
j = get_job(job_id)
assert j.get(ur.STATE_KEY) is None
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
assert datetime.fromisoformat(j["next_run_at"]) - now > timedelta(hours=11)
# One-shot: flag is ignored, no retry state, no resurrection.
- once = create_job("one shot", _iso(datetime.now(timezone.utc) + timedelta(minutes=1)))
+ once = create_job("one shot", _iso(datetime.now(UTC) + timedelta(minutes=1)))
assert mark_job_run(once["id"], False, "ConnectError: dns", model_unreachable=True)
remaining = get_job(once["id"])
assert remaining is None or remaining.get(ur.STATE_KEY) is None
@@ -136,7 +136,7 @@ def test_ladder_reruns_do_not_spend_extra_repeat_budget(tmp_cron_home, monkeypat
model calls, where the same outage with the ladder off costs it one run (#109990 fixed only
the final-run notice). Drives the tick's claim hand-off and bookkeeping tail: the claimed
snapshot's ``next_run_at`` has already moved to the natural slot when the run is recorded."""
- clock = [datetime.now(timezone.utc)]
+ clock = [datetime.now(UTC)]
monkeypatch.setattr("cron.jobs._hermes_now", lambda: clock[0])
monkeypatch.setattr(ur, "_hermes_now", lambda: clock[0])
monkeypatch.setattr(sched, "finish_execution", lambda *_a, **_kw: None)
diff --git a/tests/e2e/conftest.py b/tests/e2e/conftest.py
index e9977274d40..7b73b097a09 100644
--- a/tests/e2e/conftest.py
+++ b/tests/e2e/conftest.py
@@ -12,7 +12,7 @@ No LLM, no real platform connections.
import asyncio
import sys
import uuid
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
@@ -409,7 +409,7 @@ def make_discord_message(
guild=getattr(channel, "guild", None),
mentions=mentions, attachments=attachments,
type=getattr(discord, "MessageType", SimpleNamespace()).default,
- reference=None, created_at=datetime.now(timezone.utc),
+ reference=None, created_at=datetime.now(UTC),
create_thread=AsyncMock(),
)
diff --git a/tests/e2e/core/delivery/test_cron_virtual_clock_soak.py b/tests/e2e/core/delivery/test_cron_virtual_clock_soak.py
index 55c63314666..feebd0d7f63 100644
--- a/tests/e2e/core/delivery/test_cron_virtual_clock_soak.py
+++ b/tests/e2e/core/delivery/test_cron_virtual_clock_soak.py
@@ -35,7 +35,7 @@ import os
import sys
import threading
import time
-from datetime import date, datetime, timedelta, timezone
+from datetime import date, datetime, timedelta, timezone, UTC
from pathlib import Path
from typing import Dict, List, Optional
from zoneinfo import ZoneInfo
@@ -53,7 +53,6 @@ pytestmark = pytest.mark.skipif(
REPO_ROOT = Path(__file__).resolve().parents[4]
GRID_SECONDS = 6 * 3600 # sparse idle ticks; due/pre-due ticks are added per occurrence
HOLD_STEPS = 30 # long run: 30 x 30 s = 15 virtual minutes (> 5 min fire-claim TTL)
-UTC = timezone.utc
@dataclasses.dataclass(frozen=True)
diff --git a/tests/e2e/core/providers/test_catalog_oauth.py b/tests/e2e/core/providers/test_catalog_oauth.py
index 5ad67f5cc9a..349223f2cfb 100644
--- a/tests/e2e/core/providers/test_catalog_oauth.py
+++ b/tests/e2e/core/providers/test_catalog_oauth.py
@@ -22,7 +22,7 @@ import json
import os
import subprocess
import sys
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
from typing import Any
@@ -105,7 +105,7 @@ class Home:
def _iso(delta_s: float) -> str:
- return (datetime.now(timezone.utc) + timedelta(seconds=delta_s)).isoformat()
+ return (datetime.now(UTC) + timedelta(seconds=delta_s)).isoformat()
def _nous_state(fake: OAuthFake, access: str, refresh: str, ttl_s: int) -> dict[str, Any]:
diff --git a/tests/e2e/core/upgrade/handoff/_scenario.py b/tests/e2e/core/upgrade/handoff/_scenario.py
index 05776fb7c18..e6c1e210cf0 100644
--- a/tests/e2e/core/upgrade/handoff/_scenario.py
+++ b/tests/e2e/core/upgrade/handoff/_scenario.py
@@ -300,7 +300,7 @@ def run(column: str, root: Path) -> SimpleNamespace:
o.boots = len(X.gateway_starts(inst))
o.target = X.publish_target(inst)
- due = dt.datetime.now(dt.timezone.utc).replace(microsecond=0) + dt.timedelta(seconds=CRON_DUE_S + 5)
+ due = dt.datetime.now(dt.UTC).replace(microsecond=0) + dt.timedelta(seconds=CRON_DUE_S + 5)
cp = inst.cli("cron", "create", due.isoformat(), f"Reply with the word done. {model.cron_marker}",
"--name", model.cron_marker)
assert cp.returncode == 0, "premise: cron create failed\n" + H.describe(cp)
@@ -333,7 +333,7 @@ def run(column: str, root: Path) -> SimpleNamespace:
o.dash_new = back if back and back > 0 else None
if o.ident: # the cron ticker and the kanban dispatcher live in the gateway
- _quiet_wait(lambda: dt.datetime.now(dt.timezone.utc) > due + dt.timedelta(seconds=5), timeout=600,
+ _quiet_wait(lambda: dt.datetime.now(dt.UTC) > due + dt.timedelta(seconds=5), timeout=600,
what="the cron due time")
_quiet_wait(lambda: model.cron_calls, timeout=240, what="the cron job's provider call")
_quiet_wait(lambda: card_status(inst, o.card1) == "done" and card_status(inst, o.card2) == "done",
diff --git a/tests/e2e/core/upgrade/network/_netedge.py b/tests/e2e/core/upgrade/network/_netedge.py
index 1701a2997c9..d7f005c2fb2 100644
--- a/tests/e2e/core/upgrade/network/_netedge.py
+++ b/tests/e2e/core/upgrade/network/_netedge.py
@@ -85,7 +85,7 @@ class TestCA:
directory.mkdir(parents=True, exist_ok=True)
self._key = ec.generate_private_key(ec.SECP256R1())
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "Hermes E2E TLS Inspection Root")])
- now = datetime.datetime.now(datetime.timezone.utc)
+ now = datetime.datetime.now(datetime.UTC)
self._cert = (
x509.CertificateBuilder().subject_name(name).issuer_name(name)
.public_key(self._key.public_key()).serial_number(x509.random_serial_number())
@@ -136,7 +136,7 @@ class TestCA:
def _leaf_context(self, host: str) -> ssl.SSLContext:
x509, hashes, ser, ec, oid = self._x509, self._hashes, self._ser, self._ec, self._oid
key = ec.generate_private_key(ec.SECP256R1())
- now = datetime.datetime.now(datetime.timezone.utc)
+ now = datetime.datetime.now(datetime.UTC)
try:
san = x509.IPAddress(ipaddress.ip_address(host))
except ValueError:
diff --git a/tests/fakes/platforms/discord_standin.py b/tests/fakes/platforms/discord_standin.py
index 9fe51356bd4..472fcef6ef1 100644
--- a/tests/fakes/platforms/discord_standin.py
+++ b/tests/fakes/platforms/discord_standin.py
@@ -88,7 +88,7 @@ def _json(obj: Any, status: int = 200, headers: Optional[dict[str, str]] = None)
def _iso(ts: Optional[float] = None) -> str:
- return _dt.datetime.fromtimestamp(ts or time.time(), _dt.timezone.utc).isoformat()
+ return _dt.datetime.fromtimestamp(ts or time.time(), _dt.UTC).isoformat()
class DiscordStandin(StandinServer):
diff --git a/tests/fakes/providers/gemini_native.py b/tests/fakes/providers/gemini_native.py
index f2b4862112e..c4e0f770f90 100644
--- a/tests/fakes/providers/gemini_native.py
+++ b/tests/fakes/providers/gemini_native.py
@@ -397,7 +397,7 @@ def _write_tls_material(directory: Path) -> tuple[Path, Path, Path]:
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
- now = datetime.datetime.now(datetime.timezone.utc)
+ now = datetime.datetime.now(datetime.UTC)
ca_key = ec.generate_private_key(ec.SECP256R1())
ca_name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "hermes-e2e gemini fake CA")])
ca = (x509.CertificateBuilder().subject_name(ca_name).issuer_name(ca_name)
diff --git a/tests/fakes/providers/oauth_token_server.py b/tests/fakes/providers/oauth_token_server.py
index 4f1f2bfe3e5..dbd7b4623be 100644
--- a/tests/fakes/providers/oauth_token_server.py
+++ b/tests/fakes/providers/oauth_token_server.py
@@ -306,7 +306,7 @@ def make_test_ca(directory: Path, hosts: Iterable[str]) -> TestCA:
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
directory.mkdir(parents=True, exist_ok=True)
- now = _dt.datetime.now(_dt.timezone.utc)
+ now = _dt.datetime.now(_dt.UTC)
ca_key = ec.generate_private_key(ec.SECP256R1())
ca_name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "hermes e2e test CA")])
ca_cert = (
diff --git a/tests/fakes/providers/vertex.py b/tests/fakes/providers/vertex.py
index 4326d0ad877..839b50323ba 100644
--- a/tests/fakes/providers/vertex.py
+++ b/tests/fakes/providers/vertex.py
@@ -128,7 +128,7 @@ def _write_pem(path: Path, data: bytes) -> Path:
def make_tls_material(root: Path, hosts: list[str]) -> tuple[Path, Path, Path]:
"""A throwaway CA (PEM for ``SSL_CERT_FILE``) and a leaf for ``hosts`` signed by it."""
root.mkdir(parents=True, exist_ok=True)
- now = _dt.datetime.now(_dt.timezone.utc)
+ now = _dt.datetime.now(_dt.UTC)
ca_key = ec.generate_private_key(ec.SECP256R1())
ca_ski = x509.SubjectKeyIdentifier.from_public_key(ca_key.public_key())
ca_cert = (
diff --git a/tests/gateway/test_discord_attachment_download.py b/tests/gateway/test_discord_attachment_download.py
index b4a241f0f18..da431c7414d 100644
--- a/tests/gateway/test_discord_attachment_download.py
+++ b/tests/gateway/test_discord_attachment_download.py
@@ -60,6 +60,7 @@ _ensure_discord_mock()
from plugins.platforms.discord.adapter import DiscordAdapter
from gateway.platforms.event import MessageType
+from datetime import UTC
# Minimal valid image / audio / PDF bytes so the cache_*_from_bytes
@@ -244,7 +245,7 @@ class TestHandleMessageUsesAuthenticatedRead:
msg = SimpleNamespace(
id=1, content="", attachments=[att], mentions=[],
reference=None,
- created_at=datetime.now(timezone.utc),
+ created_at=datetime.now(UTC),
channel=chan,
author=SimpleNamespace(id=42, display_name="U", name="U"),
)
diff --git a/tests/gateway/test_discord_auto_thread_prompt_parity.py b/tests/gateway/test_discord_auto_thread_prompt_parity.py
index 0e8648c90c3..a108105c284 100644
--- a/tests/gateway/test_discord_auto_thread_prompt_parity.py
+++ b/tests/gateway/test_discord_auto_thread_prompt_parity.py
@@ -7,7 +7,7 @@ between the turns is included, so both inputs that change on turn 2 are covered.
"""
from __future__ import annotations
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from types import SimpleNamespace
from unittest.mock import AsyncMock
@@ -36,7 +36,7 @@ def _message(channel: object, message_id: int, *, mention: bool) -> SimpleNamesp
return SimpleNamespace(
id=message_id, content=("<@999> " if mention else "") + "what broke?",
mentions=[_BOT] if mention else [], attachments=[], reference=None,
- created_at=datetime.now(timezone.utc), channel=channel,
+ created_at=datetime.now(UTC), channel=channel,
author=SimpleNamespace(id=42, display_name="Alice", name="alice"))
diff --git a/tests/gateway/test_discord_auto_thread_rename_pin.py b/tests/gateway/test_discord_auto_thread_rename_pin.py
index fdd3ec043bc..f3f8ee1a4e7 100644
--- a/tests/gateway/test_discord_auto_thread_rename_pin.py
+++ b/tests/gateway/test_discord_auto_thread_rename_pin.py
@@ -7,7 +7,7 @@ from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from types import SimpleNamespace
from unittest.mock import AsyncMock
@@ -56,7 +56,7 @@ def conversation(monkeypatch: pytest.MonkeyPatch) -> Conversation:
async def turn(channel: object, message_id: int) -> str:
await adapter._handle_message(SimpleNamespace(
id=message_id, content=OPENING, mentions=[], attachments=[], reference=None,
- created_at=datetime.now(timezone.utc), channel=channel,
+ created_at=datetime.now(UTC), channel=channel,
author=SimpleNamespace(id=42, display_name="Alice", name="alice")))
source = adapter.handle_message.await_args.args[0].source
return runner._pinned_session_context_prompt(build_session_context(source, config), False, "k")
diff --git a/tests/gateway/test_discord_channel_controls.py b/tests/gateway/test_discord_channel_controls.py
index 06c0a3d5f1e..96e3dc4deff 100644
--- a/tests/gateway/test_discord_channel_controls.py
+++ b/tests/gateway/test_discord_channel_controls.py
@@ -1,7 +1,7 @@
"""Tests for Discord ignored_channels and no_thread_channels config."""
from types import SimpleNamespace
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from unittest.mock import AsyncMock, MagicMock
import sys
@@ -94,7 +94,7 @@ def make_message(*, channel, content: str, mentions=None):
mentions=list(mentions or []),
attachments=[],
reference=None,
- created_at=datetime.now(timezone.utc),
+ created_at=datetime.now(UTC),
channel=channel,
author=author,
)
diff --git a/tests/gateway/test_discord_document_handling.py b/tests/gateway/test_discord_document_handling.py
index 53e70240e3c..a66a4b8effa 100644
--- a/tests/gateway/test_discord_document_handling.py
+++ b/tests/gateway/test_discord_document_handling.py
@@ -7,7 +7,7 @@ to download, cache, and optionally inject text from non-image/audio files.
import os
import sys
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from types import SimpleNamespace
from typing import Optional
from unittest.mock import AsyncMock, MagicMock, patch
@@ -134,7 +134,7 @@ def make_message(attachments: list, content: str = "") -> SimpleNamespace:
attachments=attachments,
mentions=[],
reference=None,
- created_at=datetime.now(timezone.utc),
+ created_at=datetime.now(UTC),
channel=FakeDMChannel(),
author=SimpleNamespace(id=42, display_name="Tester", name="Tester"),
)
diff --git a/tests/gateway/test_discord_double_dispatch.py b/tests/gateway/test_discord_double_dispatch.py
index d11c024fc29..f334aee5a5e 100644
--- a/tests/gateway/test_discord_double_dispatch.py
+++ b/tests/gateway/test_discord_double_dispatch.py
@@ -16,7 +16,7 @@ Two sub-scenarios are tested:
The same dedup pre-seed must still protect against the duplicate.
"""
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from types import SimpleNamespace
from unittest.mock import AsyncMock
@@ -102,7 +102,7 @@ def _make_message(
attachments=list(attachments or []),
reference=reference,
message_snapshots=message_snapshots,
- created_at=datetime.now(timezone.utc),
+ created_at=datetime.now(UTC),
channel=channel,
author=author,
type=(
diff --git a/tests/gateway/test_discord_free_response.py b/tests/gateway/test_discord_free_response.py
index 82665f34e35..cdb13658ffa 100644
--- a/tests/gateway/test_discord_free_response.py
+++ b/tests/gateway/test_discord_free_response.py
@@ -3,7 +3,7 @@
import asyncio
import os
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import sys
@@ -139,7 +139,7 @@ def make_message(*, channel, content: str, mentions=None, msg_type=None):
mentions=list(mentions or []),
attachments=[],
reference=None,
- created_at=datetime.now(timezone.utc),
+ created_at=datetime.now(UTC),
channel=channel,
author=author,
type=msg_type if msg_type is not None else discord_platform.discord.MessageType.default,
diff --git a/tests/gateway/test_discord_missed_message_backfill.py b/tests/gateway/test_discord_missed_message_backfill.py
index 1a6797ab5cd..4c4161ceb3c 100644
--- a/tests/gateway/test_discord_missed_message_backfill.py
+++ b/tests/gateway/test_discord_missed_message_backfill.py
@@ -95,7 +95,7 @@ def make_message(*, message_id=1, author_id=42, content="please ingest", reactio
author=SimpleNamespace(id=author_id, bot=False, display_name="Emo", name="emo"),
channel=channel,
guild=getattr(channel, "guild", None),
- created_at=datetime.now(timezone.utc),
+ created_at=datetime.now(dt.UTC),
attachments=[],
mentions=list(mentions or []),
reference=None,
@@ -134,7 +134,7 @@ async def test_should_not_backfill_message_with_non_down_bot_response(adapter):
content="Done — captured it.",
author=SimpleNamespace(id=999, bot=True),
reference=SimpleNamespace(message_id=1),
- created_at=datetime.now(timezone.utc),
+ created_at=datetime.now(dt.UTC),
)
channel = FakeChannel(history_messages=[bot_reply])
message = make_message(message_id=1, channel=channel)
@@ -149,7 +149,7 @@ async def test_parent_channel_unreferenced_bot_message_does_not_suppress_backfil
content="Done — captured a different item.",
author=SimpleNamespace(id=999, bot=True),
reference=None,
- created_at=datetime.now(timezone.utc),
+ created_at=datetime.now(dt.UTC),
)
channel = FakeChannel(history_messages=[unrelated_bot_post])
message = make_message(message_id=1, channel=channel)
@@ -164,7 +164,7 @@ async def test_thread_unreferenced_bot_message_does_not_mask_request(adapter):
content="Done — captured a different request.",
author=SimpleNamespace(id=999, bot=True),
reference=None,
- created_at=datetime.now(timezone.utc),
+ created_at=datetime.now(dt.UTC),
)
thread = FakeChannel(channel_id=456, parent_id=123, history_messages=[bot_post])
message = make_message(message_id=1, channel=thread)
@@ -179,7 +179,7 @@ async def test_backfills_when_only_down_notice_exists(adapter):
content="The agent is down right now.",
author=SimpleNamespace(id=999, bot=True),
reference=SimpleNamespace(message_id=1),
- created_at=datetime.now(timezone.utc),
+ created_at=datetime.now(dt.UTC),
)
channel = FakeChannel(history_messages=[down_notice])
message = make_message(message_id=1, channel=channel)
@@ -194,7 +194,7 @@ async def test_generic_unavailable_response_counts_as_completed(adapter):
content="That package is unavailable on this platform.",
author=SimpleNamespace(id=999, bot=True),
reference=SimpleNamespace(message_id=1),
- created_at=datetime.now(timezone.utc),
+ created_at=datetime.now(dt.UTC),
)
channel = FakeChannel(history_messages=[bot_reply])
message = make_message(message_id=1, channel=channel)
@@ -337,7 +337,7 @@ def test_explicit_empty_backfill_channel_list_disables_the_scan(monkeypatch):
def test_recovery_ledger_prunes_expired_rows(adapter):
- old = (datetime.now(timezone.utc) - dt.timedelta(days=31)).isoformat()
+ old = (datetime.now(dt.UTC) - dt.timedelta(days=31)).isoformat()
def insert_old_rows(conn):
conn.execute(
@@ -555,7 +555,7 @@ async def test_stored_cursor_cannot_widen_scan_window_or_leak_into_threads(adapt
thread = RecordingChannel(channel_id=456, parent_id=123)
channel = RecordingChannel(channel_id=123, threads=[thread])
- window_floor = datetime.now(timezone.utc) - dt.timedelta(hours=1)
+ window_floor = datetime.now(dt.UTC) - dt.timedelta(hours=1)
old_cursor = ((int((window_floor - dt.timedelta(hours=11)).timestamp() * 1000) - 1420070400000) << 22)
fresh_cursor = ((int((window_floor + dt.timedelta(minutes=30)).timestamp() * 1000) - 1420070400000) << 22)
diff --git a/tests/gateway/test_discord_platform_events.py b/tests/gateway/test_discord_platform_events.py
index 1edccaf72ec..b74929a9e48 100644
--- a/tests/gateway/test_discord_platform_events.py
+++ b/tests/gateway/test_discord_platform_events.py
@@ -190,7 +190,7 @@ class TestMessageEdited:
a = _adapter()
seen = _capture(a)
after = _message(
- edited_at=_dt.datetime(2026, 8, 12, 10, 30, tzinfo=_dt.timezone.utc),
+ edited_at=_dt.datetime(2026, 8, 12, 10, 30, tzinfo=_dt.UTC),
)
asyncio.run(a._on_platform_message_edit(None, after))
diff --git a/tests/gateway/test_discord_reply_mode.py b/tests/gateway/test_discord_reply_mode.py
index 895b48bed9c..c7fb45fee06 100644
--- a/tests/gateway/test_discord_reply_mode.py
+++ b/tests/gateway/test_discord_reply_mode.py
@@ -9,7 +9,7 @@ Also covers reply_to_text extraction from incoming messages.
"""
import os
import sys
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from types import SimpleNamespace
from unittest.mock import MagicMock, AsyncMock, patch
@@ -204,7 +204,7 @@ def _make_message(*, content: str = "hi", reference=None):
mentions=[],
attachments=[],
reference=reference,
- created_at=datetime.now(timezone.utc),
+ created_at=datetime.now(UTC),
channel=FakeDMChannel(),
author=author,
)
diff --git a/tests/gateway/test_discord_turn_prompt_parity.py b/tests/gateway/test_discord_turn_prompt_parity.py
index b7c57e53422..5b9f74743db 100644
--- a/tests/gateway/test_discord_turn_prompt_parity.py
+++ b/tests/gateway/test_discord_turn_prompt_parity.py
@@ -12,7 +12,7 @@ builds the source a typed message in that channel carries, or it keys another se
from __future__ import annotations
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, MagicMock
@@ -66,7 +66,7 @@ def _adapter(monkeypatch: pytest.MonkeyPatch, bound_id: int) -> DiscordAdapter:
async def _typed(adapter: DiscordAdapter, channel: Any) -> Any:
await adapter._handle_message(SimpleNamespace(
id=123, content="what broke?", mentions=[], attachments=[], reference=None,
- created_at=datetime.now(timezone.utc), channel=channel, author=_USER,
+ created_at=datetime.now(UTC), channel=channel, author=_USER,
guild=getattr(channel, "guild", None)))
return adapter.handle_message.await_args.args[0]
diff --git a/tests/gateway/test_external_drain_control.py b/tests/gateway/test_external_drain_control.py
index 9c3e1af58a2..5b100f2be86 100644
--- a/tests/gateway/test_external_drain_control.py
+++ b/tests/gateway/test_external_drain_control.py
@@ -20,6 +20,7 @@ import gateway.drain_control as dc
from gateway.run import GatewayRunner
from gateway.platforms.event import MessageEvent, MessageType
from tests.gateway.restart_test_helpers import make_restart_runner, make_restart_source
+from datetime import UTC
# ---------------------------------------------------------------------------
@@ -136,7 +137,7 @@ class TestMarkerMaxAge:
body = dc.read_drain_request()
assert body is not None
body["requested_at"] = (
- datetime.now(timezone.utc)
+ datetime.now(UTC)
- timedelta(seconds=dc.DRAIN_REQUEST_MAX_AGE_SECONDS + 60)
).isoformat()
dc.drain_request_path().write_text(json.dumps(body), encoding="utf-8")
@@ -169,7 +170,7 @@ class TestMarkerMaxAge:
from datetime import datetime, timedelta, timezone
stale_naive = (
- datetime.now(timezone.utc)
+ datetime.now(UTC)
- timedelta(seconds=dc.DRAIN_REQUEST_MAX_AGE_SECONDS + 60)
).replace(tzinfo=None)
payload = {
@@ -192,7 +193,7 @@ class TestMarkerMaxAge:
body = dc.read_drain_request()
assert body is not None
body["requested_at"] = (
- datetime.now(timezone.utc)
+ datetime.now(UTC)
- timedelta(seconds=dc.DRAIN_REQUEST_MAX_AGE_SECONDS + offset_seconds)
).isoformat()
dc.drain_request_path().write_text(json.dumps(body), encoding="utf-8")
@@ -221,7 +222,7 @@ class TestMarkerMaxAge:
body = dc.read_drain_request()
assert body is not None
body["requested_at"] = (
- datetime.now(timezone.utc)
+ datetime.now(UTC)
- timedelta(seconds=dc.DRAIN_REQUEST_MAX_AGE_SECONDS + 60)
).isoformat()
dc.drain_request_path().write_text(json.dumps(body), encoding="utf-8")
diff --git a/tests/gateway/test_gateway_platform_event_hook.py b/tests/gateway/test_gateway_platform_event_hook.py
index d1313a9287d..35a441a4e54 100644
--- a/tests/gateway/test_gateway_platform_event_hook.py
+++ b/tests/gateway/test_gateway_platform_event_hook.py
@@ -326,7 +326,7 @@ class TestNormalizeMessageEdited:
a = _adapter()
update = _edited_update()
update.edited_message.edit_date = _dt.datetime(
- 2026, 8, 12, 10, 30, tzinfo=_dt.timezone.utc,
+ 2026, 8, 12, 10, 30, tzinfo=_dt.UTC,
)
event = a._normalize_platform_event(update)
diff --git a/tests/gateway/test_memory_status.py b/tests/gateway/test_memory_status.py
index 4d9afa4202e..9295a581c20 100644
--- a/tests/gateway/test_memory_status.py
+++ b/tests/gateway/test_memory_status.py
@@ -3,14 +3,14 @@
from __future__ import annotations
import json
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
from gateway.memory_status import classify_pressure, collect_memory_status
from gateway.shutdown_watchdog import get_loop_heartbeat_path
from gateway.lifecycle_ledger import get_lifecycle_sentinel_path
-_NOW = datetime(2026, 8, 13, 12, 0, 0, tzinfo=timezone.utc)
+_NOW = datetime(2026, 8, 13, 12, 0, 0, tzinfo=UTC)
def _write_heartbeat(
diff --git a/tests/gateway/test_message_timestamps.py b/tests/gateway/test_message_timestamps.py
index b9134b6dfd6..09e6ea7037e 100644
--- a/tests/gateway/test_message_timestamps.py
+++ b/tests/gateway/test_message_timestamps.py
@@ -1,5 +1,5 @@
import sys
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from unittest.mock import Mock
from zoneinfo import ZoneInfo
@@ -25,7 +25,7 @@ def _epoch(year, month, day, hour, minute, second):
def test_render_numeric_timestamp_preserves_instant_in_system_timezone(epoch):
# Epoch 1 is still in 1969 west of UTC. Windows rejects a naive
# astimezone() conversion there, although the Unix timestamp is positive.
- local = datetime.fromtimestamp(epoch, tz=timezone.utc).astimezone()
+ local = datetime.fromtimestamp(epoch, tz=UTC).astimezone()
prefix = safe_strftime(local, "%a %Y-%m-%d %H:%M:%S %Z")
assert render_user_content_with_timestamp("hello", epoch) == f"[{prefix}] hello"
@@ -34,7 +34,7 @@ def test_render_numeric_timestamp_preserves_instant_in_system_timezone(epoch):
@pytest.mark.platforms("windows")
@pytest.mark.parametrize("epoch", [0.0, 1.123456, 86_399.0])
def test_early_naive_iso_preserves_system_local_instant(epoch):
- local = datetime.fromtimestamp(epoch, tz=timezone.utc).astimezone()
+ local = datetime.fromtimestamp(epoch, tz=UTC).astimezone()
text = local.replace(tzinfo=None).isoformat()
assert coerce_message_timestamp(text) == pytest.approx(epoch, rel=0, abs=1e-6)
@@ -44,7 +44,7 @@ def test_early_naive_iso_preserves_system_local_instant(epoch):
@pytest.mark.parametrize("style", ["human", "iso"])
@pytest.mark.parametrize("epoch", [0.0, 1.0, 86_399.0])
def test_early_embedded_local_time_preserves_instant(style, epoch):
- local = datetime.fromtimestamp(epoch, tz=timezone.utc).astimezone()
+ local = datetime.fromtimestamp(epoch, tz=UTC).astimezone()
stamp = (safe_strftime(local, "%a %Y-%m-%d %H:%M:%S") if style == "human"
else local.replace(tzinfo=None).isoformat())
content = f"[{stamp}] hello"
@@ -60,7 +60,7 @@ def test_early_embedded_local_time_preserves_instant(style, epoch):
def test_early_embedded_local_time_replays_with_injection_on_or_off(style, enabled):
from gateway.run import _build_gateway_agent_history
- local = datetime.fromtimestamp(1.0, tz=timezone.utc).astimezone()
+ local = datetime.fromtimestamp(1.0, tz=UTC).astimezone()
stamp = (safe_strftime(local, "%a %Y-%m-%d %H:%M:%S") if style == "human"
else local.replace(tzinfo=None).isoformat())
content = f"[{stamp}] hello"
@@ -79,7 +79,7 @@ def test_early_embedded_local_time_replays_with_injection_on_or_off(style, enabl
def test_early_embedded_local_time_renders_in_observed_context():
from gateway.run import _build_gateway_agent_history
- local = datetime.fromtimestamp(1.0, tz=timezone.utc).astimezone()
+ local = datetime.fromtimestamp(1.0, tz=UTC).astimezone()
content = f"[{local.replace(tzinfo=None).isoformat()}] hello"
history, observed = _build_gateway_agent_history(
[{"role": "user", "content": content, "observed": True}],
@@ -157,7 +157,7 @@ def test_system_timezone_conversion_starts_from_aware_utc(monkeypatch):
render_user_content_with_timestamp("hello", epoch)
- datetime_spy.fromtimestamp.assert_called_once_with(epoch, tz=timezone.utc)
+ datetime_spy.fromtimestamp.assert_called_once_with(epoch, tz=UTC)
def test_render_user_content_deduplicates_existing_timestamp_and_preserves_embedded_time():
diff --git a/tests/gateway/test_multiplex_session_db_profile_scope.py b/tests/gateway/test_multiplex_session_db_profile_scope.py
index d70a941a71d..0e79164f299 100644
--- a/tests/gateway/test_multiplex_session_db_profile_scope.py
+++ b/tests/gateway/test_multiplex_session_db_profile_scope.py
@@ -26,7 +26,7 @@ where they always did.
import asyncio
import sqlite3
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from unittest.mock import MagicMock, patch
@@ -768,8 +768,8 @@ def test_compression_child_write_stays_in_the_parents_profile_store(multiplex_ho
entry = SessionEntry(
session_key=key,
session_id=parent_id,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
+ created_at=datetime.now(UTC),
+ updated_at=datetime.now(UTC),
)
store._entries[key] = entry
diff --git a/tests/gateway/test_planned_stop_accepted_debt.py b/tests/gateway/test_planned_stop_accepted_debt.py
index aa7672ab597..1fe99ac208b 100644
--- a/tests/gateway/test_planned_stop_accepted_debt.py
+++ b/tests/gateway/test_planned_stop_accepted_debt.py
@@ -12,7 +12,7 @@ import os
import sys
import threading
import time
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
import pytest
@@ -54,7 +54,7 @@ def _accepted_unrecorded(tmp_path: Path, monkeypatch, *, home_writable: bool) ->
root.chmod(0o755)
body = json.loads(marker.read_text(encoding="utf-8"))
assert body.get("accepted") is (None if home_writable else True), "premise: receipt vs stamped request"
- body["written_at"] = (datetime.now(timezone.utc) - timedelta(seconds=120)).isoformat()
+ body["written_at"] = (datetime.now(UTC) - timedelta(seconds=120)).isoformat()
marker.write_text(json.dumps(body), encoding="utf-8")
saved = pause_record.read()["token"]
assert saved["stop_sent"] == [], "premise: no checkpoint landed in the record"
diff --git a/tests/gateway/test_restart_resume_pending.py b/tests/gateway/test_restart_resume_pending.py
index f0edf00471d..8c1c533cfef 100644
--- a/tests/gateway/test_restart_resume_pending.py
+++ b/tests/gateway/test_restart_resume_pending.py
@@ -27,7 +27,7 @@ PRs #9850, #9934, #7536):
import asyncio
import os
import time
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -677,7 +677,7 @@ async def test_startup_auto_resume_freshness_survives_spring_forward(monkeypatch
marked = datetime(2026, 3, 8, 1, 50)
now = datetime(2026, 3, 8, 3, 10)
if aware_marker:
- marked = datetime.fromtimestamp(marked.timestamp(), tz=timezone.utc)
+ marked = datetime.fromtimestamp(marked.timestamp(), tz=UTC)
class _FrozenDatetime(datetime):
@classmethod
diff --git a/tests/gateway/test_send_retry_hooks.py b/tests/gateway/test_send_retry_hooks.py
index d86bc98331c..976d13c6979 100644
--- a/tests/gateway/test_send_retry_hooks.py
+++ b/tests/gateway/test_send_retry_hooks.py
@@ -7,7 +7,7 @@ the numeric form; both now go through ``agent.retry_utils.parse_retry_after_seco
"""
from email.utils import format_datetime
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from types import SimpleNamespace
from typing import Any, Dict
@@ -77,7 +77,7 @@ async def test_server_retry_after_is_honoured_by_every_adapter(monkeypatch):
def _http_date_in(seconds: int) -> str:
- return format_datetime(datetime.now(timezone.utc) + timedelta(seconds=seconds), usegmt=True)
+ return format_datetime(datetime.now(UTC) + timedelta(seconds=seconds), usegmt=True)
def test_slack_retry_after_understands_http_date():
diff --git a/tests/gateway/test_status.py b/tests/gateway/test_status.py
index 6491cd162aa..d6ea3f03593 100644
--- a/tests/gateway/test_status.py
+++ b/tests/gateway/test_status.py
@@ -11,6 +11,7 @@ from types import SimpleNamespace
import pytest
from gateway import status
+from datetime import UTC
class TestGatewayPidState:
@@ -1183,7 +1184,7 @@ class TestTakeoverMarker:
"target_start_time": 100,
"replacer_pid": 99999,
"replacer_hermes_home": str(tmp_path / "profiles" / "other"),
- "written_at": datetime.now(timezone.utc).isoformat(),
+ "written_at": datetime.now(UTC).isoformat(),
}))
result = status.consume_takeover_marker_for_self()
@@ -1205,7 +1206,7 @@ class TestTakeoverMarker:
"target_pid": os.getpid(),
"target_start_time": 100,
"replacer_pid": 99999,
- "written_at": datetime.now(timezone.utc).isoformat(),
+ "written_at": datetime.now(UTC).isoformat(),
}))
result = status.consume_takeover_marker_for_self()
@@ -1604,7 +1605,7 @@ class TestNormalizeUpdatedAt:
assert isinstance(result, str)
parsed = datetime.fromisoformat(result)
assert parsed.tzinfo is not None
- assert parsed == datetime.fromtimestamp(1750000000, tz=timezone.utc)
+ assert parsed == datetime.fromtimestamp(1750000000, tz=UTC)
def test_iso_with_z_suffix_accepted(self):
@@ -1614,7 +1615,7 @@ class TestNormalizeUpdatedAt:
assert result is not None
parsed = datetime.fromisoformat(result)
assert parsed.tzinfo is not None
- assert parsed == datetime(2026, 7, 21, 12, 0, 0, tzinfo=timezone.utc)
+ assert parsed == datetime(2026, 7, 21, 12, 0, 0, tzinfo=UTC)
def test_naive_iso_coerced_to_utc(self):
from datetime import datetime, timezone
@@ -1624,7 +1625,7 @@ class TestNormalizeUpdatedAt:
parsed = datetime.fromisoformat(result)
assert parsed.tzinfo is not None
assert parsed.utcoffset().total_seconds() == 0
- assert parsed == datetime(2026, 7, 21, 12, 0, 0, tzinfo=timezone.utc)
+ assert parsed == datetime(2026, 7, 21, 12, 0, 0, tzinfo=UTC)
def test_offset_aware_iso_round_trips_canonically(self):
canonical = "2026-07-21T12:00:00+00:00"
diff --git a/tests/hermes_cli/test_auth_nous_provider.py b/tests/hermes_cli/test_auth_nous_provider.py
index 8e1d65e04e3..22223b0a2ff 100644
--- a/tests/hermes_cli/test_auth_nous_provider.py
+++ b/tests/hermes_cli/test_auth_nous_provider.py
@@ -5,7 +5,7 @@ import json
import logging
import sys
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
import httpx
@@ -130,7 +130,7 @@ def _jwt_with_claims(claims: dict) -> str:
return f"{_part({'alg': 'none', 'typ': 'JWT'})}.{_part(claims)}.sig"
def _future_iso(seconds: int = 3600) -> str:
- return datetime.fromtimestamp(time.time() + seconds, tz=timezone.utc).isoformat()
+ return datetime.fromtimestamp(time.time() + seconds, tz=UTC).isoformat()
def _invoke_jwt(*, seconds: int = 3600, scope: object = "inference:invoke") -> str:
return _jwt_with_claims({
@@ -182,7 +182,7 @@ def test_resolve_nous_runtime_credentials_invoke_jwt_is_idempotent(
hermes_home = tmp_path / "hermes"
hermes_home.mkdir(parents=True, exist_ok=True)
exp = int(time.time() + 3600)
- expires_at = datetime.fromtimestamp(exp, tz=timezone.utc).isoformat()
+ expires_at = datetime.fromtimestamp(exp, tz=UTC).isoformat()
token = _jwt_with_claims({
"sub": "test-user",
"scope": auth_mod.DEFAULT_NOUS_SCOPE,
diff --git a/tests/hermes_cli/test_cron.py b/tests/hermes_cli/test_cron.py
index 2c05bdf6c39..e7c05e44fdb 100644
--- a/tests/hermes_cli/test_cron.py
+++ b/tests/hermes_cli/test_cron.py
@@ -3,7 +3,7 @@
import argparse
import time
from argparse import Namespace
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from types import SimpleNamespace
import pytest
@@ -225,11 +225,11 @@ class TestCronDoctor:
assert "unknown error" not in out
def test_doctor_flags_overdue_next_run(self, tmp_cron_dir, capsys):
- from datetime import datetime, timedelta, timezone
+ from datetime import datetime, timedelta
create_job(prompt="Hourly ping", schedule="every 1h")
jobs = load_jobs()
- stale = (datetime.now(timezone.utc) - timedelta(hours=3)).isoformat()
+ stale = (datetime.now(UTC) - timedelta(hours=3)).isoformat()
jobs[0]["next_run_at"] = stale
save_jobs(jobs)
@@ -241,12 +241,12 @@ class TestCronDoctor:
assert "not firing" in out
def test_doctor_tolerates_slightly_late_next_run(self, tmp_cron_dir, capsys):
- from datetime import datetime, timedelta, timezone
+ from datetime import datetime, timedelta
create_job(prompt="Hourly ping", schedule="every 1h")
jobs = load_jobs()
# 5 minutes late is within the ticker grace window — healthy.
- recent = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
+ recent = (datetime.now(UTC) - timedelta(minutes=5)).isoformat()
jobs[0]["next_run_at"] = recent
save_jobs(jobs)
@@ -592,7 +592,7 @@ class TestStatusSurfacesDeadScheduler:
):
job = create_job(prompt="Hourly", schedule="every 60m")
self._dead_gateway(monkeypatch, tmp_cron_dir / "locks")
- self._park_next_run(job["id"], datetime.now(timezone.utc) - timedelta(hours=7))
+ self._park_next_run(job["id"], datetime.now(UTC) - timedelta(hours=7))
(tmp_cron_dir / "cron" / "ticker_heartbeat").write_text(str(time.time() - 25 * 3600))
cron_command(Namespace(cron_command="status"))
@@ -613,7 +613,7 @@ class TestStatusSurfacesDeadScheduler:
# not flash OVERDUE while doctor calls the same job healthy.
job = create_job(prompt="Hourly", schedule="every 60m")
self._dead_gateway(monkeypatch, tmp_cron_dir / "locks")
- self._park_next_run(job["id"], datetime.now(timezone.utc) - timedelta(minutes=5))
+ self._park_next_run(job["id"], datetime.now(UTC) - timedelta(minutes=5))
cron_command(Namespace(cron_command="status"))
status_out = capsys.readouterr().out
@@ -635,7 +635,7 @@ class TestStatusSurfacesDeadScheduler:
stale = create_job(prompt="Hourly", schedule="every 60m")
paused = create_job(prompt="Parked", schedule="every 60m")
- when = datetime.now(timezone.utc) - timedelta(hours=7)
+ when = datetime.now(UTC) - timedelta(hours=7)
self._park_next_run(stale["id"], when)
self._park_next_run(paused["id"], when)
jobs = load_jobs()
diff --git a/tests/hermes_cli/test_cron_dispatch_visibility.py b/tests/hermes_cli/test_cron_dispatch_visibility.py
index 1c9e14b509e..e1173698d8e 100644
--- a/tests/hermes_cli/test_cron_dispatch_visibility.py
+++ b/tests/hermes_cli/test_cron_dispatch_visibility.py
@@ -5,7 +5,7 @@ disposition) and `hermes cron status` calls out jobs whose last dispatch
was a late/missed-fire catch-up.
"""
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
import pytest
@@ -32,7 +32,7 @@ def _stamp_last_dispatch(job_id, stamp):
save_jobs(jobs)
def _catch_up_stamp(late_seconds=1860.0, kind="catch_up"):
- scheduled = datetime(2026, 9, 1, 9, 0, tzinfo=timezone.utc)
+ scheduled = datetime(2026, 9, 1, 9, 0, tzinfo=UTC)
return {
"scheduled_at": scheduled.isoformat(),
"dispatched_at": (scheduled + timedelta(seconds=late_seconds)).isoformat(),
diff --git a/tests/hermes_cli/test_cron_satellite_diagnostics.py b/tests/hermes_cli/test_cron_satellite_diagnostics.py
index 7a4a8098ed7..fa1f5a2dec5 100644
--- a/tests/hermes_cli/test_cron_satellite_diagnostics.py
+++ b/tests/hermes_cli/test_cron_satellite_diagnostics.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
import json
import os
import time
@@ -281,7 +281,7 @@ def test_doctor_reports_persisted_dispatch_health(served_root, capsys, dispatch)
else:
records = jobs.load_jobs()
delay = timedelta(hours=5) if dispatch == "catch_up" else timedelta(minutes=6)
- records[0]["next_run_at"] = (datetime.now(timezone.utc) - delay).isoformat()
+ records[0]["next_run_at"] = (datetime.now(UTC) - delay).isoformat()
jobs.save_jobs(records)
assert len(jobs.get_due_jobs()) == 1
persisted = jobs.get_job(job["id"])
@@ -300,7 +300,7 @@ def test_doctor_reports_persisted_dispatch_health(served_root, capsys, dispatch)
assert cron_doctor() == 1
capsys.readouterr()
records = jobs.load_jobs()
- records[0]["next_run_at"] = datetime.now(timezone.utc).isoformat()
+ records[0]["next_run_at"] = datetime.now(UTC).isoformat()
jobs.save_jobs(records)
assert len(jobs.get_due_jobs()) == 1
persisted = jobs.get_job(job["id"])
diff --git a/tests/hermes_cli/test_curator_recent_run_notice.py b/tests/hermes_cli/test_curator_recent_run_notice.py
index 3f6dcb756a3..c4e7e555d00 100644
--- a/tests/hermes_cli/test_curator_recent_run_notice.py
+++ b/tests/hermes_cli/test_curator_recent_run_notice.py
@@ -12,7 +12,7 @@ is the high-attention surface where consolidations should land.
from __future__ import annotations
import importlib
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
import pytest
@@ -51,7 +51,7 @@ def _set_state(curator_mod, **fields):
def test_silent_when_summary_is_single_line(curator_env):
"""No archives = no rename map = nothing to surface. But still stamps shown."""
- now = datetime.now(timezone.utc).isoformat()
+ now = datetime.now(UTC).isoformat()
_set_state(
curator_env["curator"],
last_run_at=now,
@@ -74,7 +74,7 @@ def test_silent_when_summary_is_single_line(curator_env):
def test_format_time_ago_buckets(curator_env):
"""Smoke test the time formatter — drives the `last run Xh ago` line."""
fmt = curator_env["main"]._format_time_ago
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
assert fmt((now - timedelta(seconds=10)).isoformat()) == "just now"
assert fmt((now - timedelta(minutes=5)).isoformat()) == "5m ago"
assert fmt((now - timedelta(hours=3)).isoformat()) == "3h ago"
diff --git a/tests/hermes_cli/test_gateway_multiplex_mode.py b/tests/hermes_cli/test_gateway_multiplex_mode.py
index d2c380a9fe6..575eaed4a42 100644
--- a/tests/hermes_cli/test_gateway_multiplex_mode.py
+++ b/tests/hermes_cli/test_gateway_multiplex_mode.py
@@ -20,6 +20,7 @@ import hermes_constants
from gateway.config import GatewayConfig, load_gateway_config
from hermes_cli import gateway_migrate as gm
from hermes_cli import gateway_multiplex_mode as mode
+from datetime import UTC
@pytest.fixture
@@ -202,7 +203,7 @@ def test_recorded_standalone_warning_lines_suppressed_for_dead_or_stale_record(t
state_file.write_text(json.dumps({
"gateway_state": "stopped",
"pid": os.getpid(),
- "updated_at": datetime.now(timezone.utc).isoformat(),
+ "updated_at": datetime.now(UTC).isoformat(),
"multiplex_standalone_reason": "orphan reason",
}), encoding="utf-8")
assert mode.recorded_standalone_warning_lines() == []
@@ -211,7 +212,7 @@ def test_recorded_standalone_warning_lines_suppressed_for_dead_or_stale_record(t
state_file.write_text(json.dumps({
"gateway_state": "running",
"pid": 999999999,
- "updated_at": datetime.now(timezone.utc).isoformat(),
+ "updated_at": datetime.now(UTC).isoformat(),
"multiplex_standalone_reason": "orphan reason",
}), encoding="utf-8")
monkeypatch.setattr(gw_status, "runtime_status_pid_is_live", lambda r: False)
@@ -232,7 +233,7 @@ def test_recorded_standalone_warning_lines_suppressed_for_dead_or_stale_record(t
state_file.write_text(json.dumps({
"gateway_state": "running",
"pid": os.getpid(),
- "updated_at": datetime.now(timezone.utc).isoformat(),
+ "updated_at": datetime.now(UTC).isoformat(),
"multiplex_standalone_reason": "real standalone reason",
}), encoding="utf-8")
monkeypatch.setattr(gw_status, "runtime_status_pid_is_live", lambda r: True)
diff --git a/tests/hermes_cli/test_gateway_runtime_health.py b/tests/hermes_cli/test_gateway_runtime_health.py
index e5f28e842e4..940fc8b0c84 100644
--- a/tests/hermes_cli/test_gateway_runtime_health.py
+++ b/tests/hermes_cli/test_gateway_runtime_health.py
@@ -1,11 +1,11 @@
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from hermes_cli.gateway import _runtime_health_lines
def _iso_age(seconds_ago: float) -> str:
"""ISO-8601 UTC timestamp ``seconds_ago`` in the past (drives _marker_is_stale)."""
- return (datetime.now(timezone.utc) - timedelta(seconds=seconds_ago)).isoformat()
+ return (datetime.now(UTC) - timedelta(seconds=seconds_ago)).isoformat()
_STALE_LINE_PREFIX = "⚠ Stale gateway_state.json:"
diff --git a/tests/hermes_cli/test_minimax_oauth.py b/tests/hermes_cli/test_minimax_oauth.py
index 776abeea630..face4104e3e 100644
--- a/tests/hermes_cli/test_minimax_oauth.py
+++ b/tests/hermes_cli/test_minimax_oauth.py
@@ -16,7 +16,7 @@ import json
import threading
import time
import urllib.parse
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from unittest.mock import MagicMock, patch
import pytest
@@ -64,18 +64,18 @@ def _make_httpx_response(status_code: int, body: dict | None = None, text: str =
def _future_iso(seconds_from_now: int = 3600) -> str:
ts = time.time() + seconds_from_now
- return datetime.fromtimestamp(ts, tz=timezone.utc).isoformat()
+ return datetime.fromtimestamp(ts, tz=UTC).isoformat()
def _past_iso(seconds_ago: int = 3600) -> str:
ts = time.time() - seconds_ago
- return datetime.fromtimestamp(ts, tz=timezone.utc).isoformat()
+ return datetime.fromtimestamp(ts, tz=UTC).isoformat()
# ---------------------------------------------------------------------------
# 0. test_resolve_token_expiry_unix_ttl_vs_absolute_ms
# ---------------------------------------------------------------------------
def test_resolve_token_expiry_unix_ttl_seconds():
- now = datetime(2025, 6, 1, 12, 0, 0, tzinfo=timezone.utc)
+ now = datetime(2025, 6, 1, 12, 0, 0, tzinfo=UTC)
got = _minimax_resolve_token_expiry_unix(3600, now=now)
assert abs(got - (now.timestamp() + 3600)) < 0.01
diff --git a/tests/hermes_cli/test_model_options_account_usage.py b/tests/hermes_cli/test_model_options_account_usage.py
index 1f9750665b6..c920d16333d 100644
--- a/tests/hermes_cli/test_model_options_account_usage.py
+++ b/tests/hermes_cli/test_model_options_account_usage.py
@@ -6,7 +6,7 @@ refresh in the background: a slow or hung usage endpoint can't be allowed to sta
import threading
import time
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from agent import account_usage
from agent.account_usage import AccountUsageSnapshot, AccountUsageWindow
@@ -15,9 +15,9 @@ from hermes_cli.inventory import build_model_options_payload, load_picker_contex
def _snapshot(used: float) -> AccountUsageSnapshot:
- reset = datetime.now(timezone.utc) + timedelta(hours=2)
+ reset = datetime.now(UTC) + timedelta(hours=2)
return AccountUsageSnapshot(
- provider="openrouter", source="test", fetched_at=datetime.now(timezone.utc),
+ provider="openrouter", source="test", fetched_at=datetime.now(UTC),
windows=(AccountUsageWindow(label="Current session", used_percent=used, reset_at=reset),))
@@ -48,4 +48,4 @@ def test_picker_reads_cached_usage_and_refreshes_without_waiting(monkeypatch):
row = next(r for r in build_model_options_payload(ctx)["providers"] if r["slug"] == "openrouter")
(window,) = row["usage"]["windows"]
assert window["label"] == "Current session" and window["used_percent"] == 92.0
- assert datetime.fromisoformat(window["resets_at"]) > datetime.now(timezone.utc)
+ assert datetime.fromisoformat(window["resets_at"]) > datetime.now(UTC)
diff --git a/tests/hermes_cli/test_model_options_pool_usage.py b/tests/hermes_cli/test_model_options_pool_usage.py
index 602d644d7cc..d4633166faf 100644
--- a/tests/hermes_cli/test_model_options_pool_usage.py
+++ b/tests/hermes_cli/test_model_options_pool_usage.py
@@ -12,7 +12,7 @@ from __future__ import annotations
import json
import threading
import time
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
import pytest
@@ -48,9 +48,9 @@ def _fp(token: str) -> str:
def _snapshot(used: float, *, resets_in_hours: float = 2.0, scope: str = "account") -> AccountUsageSnapshot:
return AccountUsageSnapshot(
- provider="openrouter", source="test", fetched_at=datetime.now(timezone.utc),
+ provider="openrouter", source="test", fetched_at=datetime.now(UTC),
windows=(AccountUsageWindow(label="API key quota", used_percent=used,
- reset_at=datetime.now(timezone.utc) + timedelta(hours=resets_in_hours),
+ reset_at=datetime.now(UTC) + timedelta(hours=resets_in_hours),
scope=scope),))
@@ -181,7 +181,7 @@ def test_limited_account_resets_at_is_latest_exhausted_window(monkeypatch, tmp_p
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "a"))
_write_pool(tmp_path / "a", "openrouter", [_entry("c1", "tok-1"), _entry("c2", "tok-2")])
_clear_cache()
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
snapshot = AccountUsageSnapshot(
provider="openrouter", source="test", fetched_at=now,
windows=(
@@ -221,7 +221,7 @@ def test_live_cooldown_marks_account_limited_without_mutating_pool(monkeypatch,
from datetime import datetime as _dt
assert accounts[_fp("tok-1")]["state"] == "limited"
- assert accounts[_fp("tok-1")]["resets_at"] == _dt.fromtimestamp(reset_at, timezone.utc).isoformat()
+ assert accounts[_fp("tok-1")]["resets_at"] == _dt.fromtimestamp(reset_at, UTC).isoformat()
assert accounts[_fp("tok-2")]["state"] == "ready", "a benched sibling never hides a healthy account"
disk = json.loads((tmp_path / "a" / "auth.json").read_text())
assert len(disk["credential_pool"]["openrouter"]) == 2, "read path must not prune or rewrite the pool"
@@ -356,7 +356,7 @@ def test_model_scoped_window_exhaustion_does_not_limit_account(monkeypatch, tmp_
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "a"))
_write_pool(tmp_path / "a", "openrouter", [_entry("c1", "tok-1"), _entry("c2", "tok-2")])
_clear_cache()
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
snapshot = AccountUsageSnapshot(
provider="openrouter", source="test", fetched_at=now,
windows=(AccountUsageWindow(label="Opus week", used_percent=100.0,
diff --git a/tests/hermes_cli/test_profile_distribution.py b/tests/hermes_cli/test_profile_distribution.py
index 41d1d045263..c42ba1d1ca6 100644
--- a/tests/hermes_cli/test_profile_distribution.py
+++ b/tests/hermes_cli/test_profile_distribution.py
@@ -15,7 +15,7 @@ import shutil
import stat
import subprocess
import sys
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
from types import SimpleNamespace
@@ -375,7 +375,7 @@ class TestInstall:
with use_cron_store(staged):
shipped = list_jobs(include_disabled=True)[0]
update_job(shipped["id"], {
- "next_run_at": (datetime.now(timezone.utc) - timedelta(days=2)).isoformat()
+ "next_run_at": (datetime.now(UTC) - timedelta(days=2)).isoformat()
})
(staged / "cron" / "future-runtime.bin").write_text("runtime", encoding="utf-8")
(staged / "skills" / ".future-runtime").write_text("runtime", encoding="utf-8")
@@ -830,7 +830,7 @@ class TestInstalledAtStamp:
class _FakeDT(_dt.datetime):
@classmethod
def now(cls, tz=None):
- return _dt.datetime(2099, 1, 1, 0, 0, 0, tzinfo=tz or _dt.timezone.utc)
+ return _dt.datetime(2099, 1, 1, 0, 0, 0, tzinfo=tz or _dt.UTC)
monkeypatch.setattr(
"hermes_cli.profile_distribution.datetime", _FakeDT, raising=True
)
diff --git a/tests/hermes_cli/test_relay_shared_metrics.py b/tests/hermes_cli/test_relay_shared_metrics.py
index ce4d605df29..a1a130305da 100644
--- a/tests/hermes_cli/test_relay_shared_metrics.py
+++ b/tests/hermes_cli/test_relay_shared_metrics.py
@@ -13,7 +13,7 @@ import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from copy import deepcopy
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -338,14 +338,14 @@ def test_v1_outbox_package_exports_unchanged_after_upgrade(tmp_path):
def test_due_export_runs_once_per_utc_day_and_catches_up_pending_deltas(
tmp_path, monkeypatch
):
- current_time = datetime(2026, 7, 28, 9, tzinfo=timezone.utc)
+ current_time = datetime(2026, 7, 28, 9, tzinfo=UTC)
monkeypatch.setattr(shared_metrics_module, "_utc_now", lambda: current_time)
store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")
store.record_model_call(_dimensions(), _resource())
assert len(store.create_and_export_package_if_due()) == 1
- current_time = datetime(2026, 7, 28, 18, tzinfo=timezone.utc)
+ current_time = datetime(2026, 7, 28, 18, tzinfo=UTC)
store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")
store.record_model_call(_dimensions(), _resource())
assert store.create_and_export_package_if_due() == []
@@ -359,7 +359,7 @@ def test_due_export_runs_once_per_utc_day_and_catches_up_pending_deltas(
"packaged_value": 1,
}
- current_time = datetime(2026, 7, 29, 9, tzinfo=timezone.utc)
+ current_time = datetime(2026, 7, 29, 9, tzinfo=UTC)
store.record_model_call(_dimensions(), _resource())
assert len(store.create_and_export_package_if_due()) == 2
assert len(list((tmp_path / "outbox").glob("*.json"))) == 3
@@ -379,7 +379,7 @@ def test_client_active_uses_a_transactional_rolling_24_hour_latch(
database_path = tmp_path / "metrics.sqlite3"
outbox_directory = tmp_path / "outbox"
store = SharedMetricsStore(database_path, outbox_directory)
- now = datetime(2026, 7, 22, 10, 0, tzinfo=timezone.utc)
+ now = datetime(2026, 7, 22, 10, 0, tzinfo=UTC)
monkeypatch.setattr(shared_metrics_module, "_utc_now", lambda: now)
assert store.record_client_active(_resource())
@@ -415,7 +415,7 @@ def test_client_active_recovers_from_an_invalid_latch_and_creates_identity(
"INSERT INTO telemetry_state(key, value) VALUES (?, ?)",
("client_active_recorded_at", "invalid-timestamp"),
)
- now = datetime(2026, 7, 22, 10, 0, tzinfo=timezone.utc)
+ now = datetime(2026, 7, 22, 10, 0, tzinfo=UTC)
monkeypatch.setattr(shared_metrics_module, "_utc_now", lambda: now)
assert store.record_client_active(_resource())
@@ -436,7 +436,7 @@ def test_client_active_rebases_a_future_latch_without_double_counting(
):
database_path = tmp_path / "metrics.sqlite3"
store = SharedMetricsStore(database_path, tmp_path / "outbox")
- now = datetime(2026, 7, 22, 10, 0, tzinfo=timezone.utc)
+ now = datetime(2026, 7, 22, 10, 0, tzinfo=UTC)
monkeypatch.setattr(shared_metrics_module, "_utc_now", lambda: now)
assert store.record_client_active(_resource())
@@ -1311,7 +1311,7 @@ def test_retention_prunes_only_expired_exported_history(tmp_path):
)
store._prune_expired_history(
- now=datetime(2026, 7, 23, tzinfo=timezone.utc)
+ now=datetime(2026, 7, 23, tzinfo=UTC)
)
assert not expired_path.exists()
diff --git a/tests/hermes_cli/test_relay_shared_metrics_runtime.py b/tests/hermes_cli/test_relay_shared_metrics_runtime.py
index 749b1894395..397ecaf0c64 100644
--- a/tests/hermes_cli/test_relay_shared_metrics_runtime.py
+++ b/tests/hermes_cli/test_relay_shared_metrics_runtime.py
@@ -6,7 +6,7 @@ import contextvars
import json
import sqlite3
import threading
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from types import SimpleNamespace
from typing import Any
@@ -668,7 +668,7 @@ def test_real_binding_drives_lifecycle_aggregation_export_and_snapshot(
_join_export_workers()
root = tmp_path / "hermes-home" / "telemetry" / "shared_metrics"
store = SharedMetricsStore(root / "metrics.sqlite3", root / "outbox")
- tomorrow = datetime.now(timezone.utc) + timedelta(days=1)
+ tomorrow = datetime.now(UTC) + timedelta(days=1)
monkeypatch.setattr(
"hermes_cli.observability.shared_metrics._utc_now",
lambda: tomorrow,
@@ -2460,7 +2460,7 @@ def test_task_retry_count_survives_provider_fallback_ordinal_reset(direct_runtim
def test_failed_flush_keeps_daily_export_open_for_later_task(
direct_runtime, tmp_path, monkeypatch, caplog
):
- current_time = datetime(2026, 7, 28, 9, tzinfo=timezone.utc)
+ current_time = datetime(2026, 7, 28, 9, tzinfo=UTC)
monkeypatch.setattr(
"hermes_cli.observability.shared_metrics._utc_now",
lambda: current_time,
@@ -2532,7 +2532,7 @@ def parked_flush(direct_runtime, monkeypatch):
"""A flush that blocks like the real barrier does while another session's tool runs."""
monkeypatch.setattr(
"hermes_cli.observability.shared_metrics._utc_now",
- lambda: datetime(2026, 7, 28, 9, tzinfo=timezone.utc),
+ lambda: datetime(2026, 7, 28, 9, tzinfo=UTC),
)
state = SimpleNamespace(attempts=0, entered=threading.Event(), release=threading.Event())
diff --git a/tests/hermes_cli/test_shared_metrics_consent_windows.py b/tests/hermes_cli/test_shared_metrics_consent_windows.py
index 66b58d5dd3a..b6a33de8ec5 100644
--- a/tests/hermes_cli/test_shared_metrics_consent_windows.py
+++ b/tests/hermes_cli/test_shared_metrics_consent_windows.py
@@ -11,7 +11,7 @@ reconciler rather than a model of them.
from __future__ import annotations
import json
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
import pytest
@@ -22,7 +22,7 @@ from hermes_cli.observability.shared_metrics_sender import (
)
from hermes_cli.sqlite_util import write_txn
-T0 = datetime(2026, 8, 1, tzinfo=timezone.utc)
+T0 = datetime(2026, 8, 1, tzinfo=UTC)
def ts(days=0, hours=0):
@@ -142,7 +142,7 @@ class TestClockAdversaries:
the window back to the true revoke moment.
"""
_observe(store, True, dt(0))
- _observe(store, True, datetime(2099, 1, 1, tzinfo=timezone.utc))
+ _observe(store, True, datetime(2099, 1, 1, tzinfo=UTC))
_observe(store, False, dt(1)) # honest clock at revoke
for n in range(2, 10):
_add(store, f"REFUSED-{n}", ts(days=n), ts(days=n, hours=2))
@@ -163,7 +163,7 @@ class TestClockAdversaries:
)
_observe(store, True, dt(0))
- _observe(store, True, datetime(2099, 1, 1, tzinfo=timezone.utc))
+ _observe(store, True, datetime(2099, 1, 1, tzinfo=UTC))
with store._connection() as connection:
stamp = connection.execute(
"SELECT stamp FROM consent_marks WHERE name = 'obs'"
diff --git a/tests/hermes_cli/test_shared_metrics_engagement.py b/tests/hermes_cli/test_shared_metrics_engagement.py
index 2b3832daea1..f17e662edf0 100644
--- a/tests/hermes_cli/test_shared_metrics_engagement.py
+++ b/tests/hermes_cli/test_shared_metrics_engagement.py
@@ -4,7 +4,7 @@ conversation is one session row with its whole volume, and turns-before-switch n
from __future__ import annotations
import json
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
import pytest
@@ -20,7 +20,7 @@ from tests.hermes_cli.test_relay_shared_metrics_runtime import (
PUBLIC = "anthropic/claude-sonnet-4"
OTHER = "openai/gpt-5"
-DAY1 = datetime(2026, 9, 27, 9, 0, tzinfo=timezone.utc).timestamp()
+DAY1 = datetime(2026, 9, 27, 9, 0, tzinfo=UTC).timestamp()
def _flush() -> None:
@@ -110,7 +110,7 @@ def test_a_late_interaction_never_reopens_a_closed_day():
"""An interaction sampled before midnight that lands after the day rolled folds into the newer day:
the closed day is reported once, and the only close path is a later clock."""
resource = {"architecture": "x86_64", "hermes_version": "0.0.0", "install_method": "git", "os_family": "linux"}
- midnight = int(datetime(2026, 9, 28, tzinfo=timezone.utc).timestamp() * 1000)
+ midnight = int(datetime(2026, 9, 28, tzinfo=UTC).timestamp() * 1000)
state, _ = engagement.apply(None, now_ms=midnight - 3_600_000, resource=resource, surface="cli")
state, closed = engagement.apply(state, now_ms=midnight + 500, resource=resource, surface="cli")
assert [r[3] for r in closed] == ["2026-09-27", "2026-09-27"]
diff --git a/tests/hermes_cli/test_shared_metrics_install_run.py b/tests/hermes_cli/test_shared_metrics_install_run.py
index f9663cd4463..2c50a70a7f1 100644
--- a/tests/hermes_cli/test_shared_metrics_install_run.py
+++ b/tests/hermes_cli/test_shared_metrics_install_run.py
@@ -11,7 +11,7 @@ import sqlite3
import subprocess
import sys
import time
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
from types import SimpleNamespace
@@ -176,7 +176,7 @@ def test_receipt_is_recorded_only_on_a_day_the_sender_can_ever_send(marks, monke
from hermes_cli.observability.shared_metrics_sender import CONSENT_GATE_SQL, reconcile_send_consent
from hermes_cli.sqlite_util import write_txn
- t0 = datetime(2026, 10, 6, tzinfo=timezone.utc)
+ t0 = datetime(2026, 10, 6, tzinfo=UTC)
clock = {"now": t0 + timedelta(hours=9)}
monkeypatch.setattr(store_module, "_utc_now", lambda: clock["now"])
monkeypatch.setattr("hermes_cli.config.read_raw_config_readonly",
diff --git a/tests/hermes_cli/test_shared_metrics_reliability.py b/tests/hermes_cli/test_shared_metrics_reliability.py
index 8206179a0c1..685f4d94be9 100644
--- a/tests/hermes_cli/test_shared_metrics_reliability.py
+++ b/tests/hermes_cli/test_shared_metrics_reliability.py
@@ -7,7 +7,7 @@ import json
import os
import subprocess
import sys
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from types import SimpleNamespace
import pytest
@@ -43,7 +43,7 @@ def marks(tmp_path, monkeypatch):
def _identity(monkeypatch, *shas: str) -> None:
- committed = int((datetime.now(timezone.utc) - timedelta(days=10)).timestamp())
+ committed = int((datetime.now(UTC) - timedelta(days=10)).timestamp())
sequence = iter(shas)
last = {"sha": shas[0]}
diff --git a/tests/hermes_cli/test_shared_metrics_sender.py b/tests/hermes_cli/test_shared_metrics_sender.py
index dc363292d31..579aa8c9e64 100644
--- a/tests/hermes_cli/test_shared_metrics_sender.py
+++ b/tests/hermes_cli/test_shared_metrics_sender.py
@@ -9,7 +9,7 @@ user's local history rather than a send queue.
from __future__ import annotations
import json
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
import pytest
@@ -25,7 +25,7 @@ from hermes_cli.observability.shared_metrics_sender import (
from hermes_cli.sqlite_util import write_txn
INSTALL_ID = "12a73e97-4de9-4766-830d-9ca1192c0420"
-NOW = datetime(2026, 8, 26, 12, 0, tzinfo=timezone.utc)
+NOW = datetime(2026, 8, 26, 12, 0, tzinfo=UTC)
ENDPOINT = "https://telemetry.test/v1/telemetry"
@@ -76,8 +76,8 @@ def store(tmp_path):
def _grant_consent(
store,
- opened=datetime(2026, 8, 20, tzinfo=timezone.utc),
- confirmed_through=datetime(2026, 10, 1, tzinfo=timezone.utc),
+ opened=datetime(2026, 8, 20, tzinfo=UTC),
+ confirmed_through=datetime(2026, 10, 1, tzinfo=UTC),
):
"""Open a consent window and heartbeat it forward, via the real writer."""
with store._connection() as connection:
@@ -152,7 +152,7 @@ def _row(store, package_id):
def _iso(moment):
- return moment.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
+ return moment.astimezone(UTC).isoformat().replace("+00:00", "Z")
def _sender(store, transport, **kwargs):
@@ -266,7 +266,7 @@ class TestConsentGate:
def test_packages_from_before_opt_in_are_never_sent(self, store):
# Consent opens on Aug 24; the "old" package's period predates it.
_clear_consent(store)
- _grant_consent(store, opened=datetime(2026, 8, 24, tzinfo=timezone.utc))
+ _grant_consent(store, opened=datetime(2026, 8, 24, tzinfo=UTC))
_add_package(store, "old", "2026-08-20")
_add_package(store, "new", "2026-08-26")
transport = FakeTransport(FakeResponse(202))
diff --git a/tests/hermes_cli/test_shared_metrics_sender_e2e.py b/tests/hermes_cli/test_shared_metrics_sender_e2e.py
index 68537835f7d..355d57a7ee8 100644
--- a/tests/hermes_cli/test_shared_metrics_sender_e2e.py
+++ b/tests/hermes_cli/test_shared_metrics_sender_e2e.py
@@ -10,7 +10,7 @@ from __future__ import annotations
import gzip
import json
import threading
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from http.server import BaseHTTPRequestHandler, HTTPServer
import pytest
@@ -19,7 +19,7 @@ from hermes_cli.observability.shared_metrics import SharedMetricsStore
from hermes_cli.observability.shared_metrics_sender import SharedMetricsSender
INSTALL_ID = "12a73e97-4de9-4766-830d-9ca1192c0420"
-NOW = datetime(2026, 8, 26, 12, 0, tzinfo=timezone.utc)
+NOW = datetime(2026, 8, 26, 12, 0, tzinfo=UTC)
class Ingest(BaseHTTPRequestHandler):
@@ -82,7 +82,7 @@ def store(tmp_path):
)
# Open a consent window covering the fixture packages; the interval gate
# fails closed without one, and this file tests transport, not consent.
- from datetime import datetime, timezone
+ from datetime import datetime
from hermes_cli.observability.shared_metrics_sender import (
reconcile_send_consent,
@@ -92,10 +92,10 @@ def store(tmp_path):
with built._connection() as connection:
with write_txn(connection):
reconcile_send_consent(
- connection, True, now=datetime(2026, 8, 20, tzinfo=timezone.utc)
+ connection, True, now=datetime(2026, 8, 20, tzinfo=UTC)
)
reconcile_send_consent(
- connection, True, now=datetime(2026, 10, 1, tzinfo=timezone.utc)
+ connection, True, now=datetime(2026, 10, 1, tzinfo=UTC)
)
return built
diff --git a/tests/hermes_cli/test_update_autostash.py b/tests/hermes_cli/test_update_autostash.py
index f912b7715df..f3239ebad2e 100644
--- a/tests/hermes_cli/test_update_autostash.py
+++ b/tests/hermes_cli/test_update_autostash.py
@@ -8,6 +8,7 @@ import pytest
from hermes_cli import main as hermes_main, update_cmd
from tests.hermes_cli.test_update_target_identity import git, update_tree
+from datetime import UTC
@pytest.mark.parametrize('history,failure,keep', [
@@ -88,7 +89,7 @@ def test_rescue_retention_uses_real_refs(tmp_path, monkeypatch, mode):
git(tmp_path, 'init', '-q', '-b', 'main')
git(tmp_path, '-c', 'user.name=Fixture', '-c', '[email protected]',
'-c', 'commit.gpgsign=false', 'commit', '--allow-empty', '-qm', 'base')
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
prefix = 'refs/hermes-update-backups/orphan-main-'
if mode == 'count':
refs = [prefix + (now - timedelta(hours=20-i)).strftime('%Y%m%d-%H%M%S') + '-abc'
diff --git a/tests/hermes_cli/test_update_autostash_orphan_warning.py b/tests/hermes_cli/test_update_autostash_orphan_warning.py
index 99b932560bf..25d234ccbb3 100644
--- a/tests/hermes_cli/test_update_autostash_orphan_warning.py
+++ b/tests/hermes_cli/test_update_autostash_orphan_warning.py
@@ -9,7 +9,7 @@ test.
"""
import subprocess
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
import pytest
@@ -37,7 +37,7 @@ def _make_repo_with_autostash(tmp_path, age_days: float):
(tmp_path / "tracked.txt").write_text("local change\n")
stamp = (
- datetime.now(timezone.utc) - timedelta(days=age_days)
+ datetime.now(UTC) - timedelta(days=age_days)
).strftime("%Y%m%d-%H%M%S")
name = f"hermes-update-autostash-{stamp}"
_git(tmp_path, "stash", "push", "--include-untracked", "-m", name)
diff --git a/tests/hermes_cli/test_update_pause_record.py b/tests/hermes_cli/test_update_pause_record.py
index e82375c0299..98b6c457e7a 100644
--- a/tests/hermes_cli/test_update_pause_record.py
+++ b/tests/hermes_cli/test_update_pause_record.py
@@ -14,6 +14,7 @@ from pathlib import Path
import pytest
from hermes_cli import update_pause_record as pause_record
+from datetime import UTC
REPO = Path(__file__).resolve().parents[2]
pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX signals; Windows cells live in wine2e")
@@ -708,7 +709,7 @@ def test_an_accepted_stop_the_record_could_not_checkpoint_outlives_the_request_t
saved = pause_record.read()["token"]
assert saved["stop_sent"] == [], "premise: no checkpoint landed"
body = json.loads(marker.read_text(encoding="utf-8"))
- body["written_at"] = (datetime.now(timezone.utc) - timedelta(seconds=120)).isoformat() # past the TTL
+ body["written_at"] = (datetime.now(UTC) - timedelta(seconds=120)).isoformat() # past the TTL
marker.write_text(json.dumps(body), encoding="utf-8")
owed = pause_record.drop_never_stopped(dict(saved))["profiles"]
assert owed == ({"p": pid} if consumed else {}), "a gateway draining an accepted stop lost its restart debt"
diff --git a/tests/hermes_cli/test_update_pause_stop_evidence.py b/tests/hermes_cli/test_update_pause_stop_evidence.py
index d28497c53c8..3e2ff44d8f5 100644
--- a/tests/hermes_cli/test_update_pause_stop_evidence.py
+++ b/tests/hermes_cli/test_update_pause_stop_evidence.py
@@ -10,7 +10,7 @@ from __future__ import annotations
import json
import os
import sys
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
import pytest
@@ -48,7 +48,7 @@ def _accepted_then_orphaned(tmp_path: Path, monkeypatch, *, home_writable: bool)
saved = pause_record.read()["token"]
assert saved["stop_sent"] == [], "premise: no checkpoint landed in the record"
body = json.loads(marker.read_text(encoding="utf-8"))
- body["written_at"] = (datetime.now(timezone.utc) - timedelta(seconds=120)).isoformat() # past the TTL
+ body["written_at"] = (datetime.now(UTC) - timedelta(seconds=120)).isoformat() # past the TTL
marker.write_text(json.dumps(body), encoding="utf-8")
pause_record.write(saved, owner=pause_record.UNOWNED) # the updater died
return marker, saved["pause_id"]
diff --git a/tests/hermes_cli/test_usage_command.py b/tests/hermes_cli/test_usage_command.py
index f6d68c855d5..c2208915aa1 100644
--- a/tests/hermes_cli/test_usage_command.py
+++ b/tests/hermes_cli/test_usage_command.py
@@ -6,17 +6,17 @@ Drives the real ``hermes`` argparse entrypoint; only the network fetch is replac
import json
import sys
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from unittest.mock import patch
from agent.account_usage import AccountUsageSnapshot, AccountUsageWindow
from hermes_cli import main as hermes_main
_SNAPSHOT = AccountUsageSnapshot(
- provider="openai-codex", source="usage_api", fetched_at=datetime(2026, 9, 19, 12, 0, tzinfo=timezone.utc),
+ provider="openai-codex", source="usage_api", fetched_at=datetime(2026, 9, 19, 12, 0, tzinfo=UTC),
plan="Plus",
windows=(
- AccountUsageWindow(label="Session", used_percent=37.0, reset_at=datetime(2026, 9, 19, 21, 0, tzinfo=timezone.utc)),
+ AccountUsageWindow(label="Session", used_percent=37.0, reset_at=datetime(2026, 9, 19, 21, 0, tzinfo=UTC)),
AccountUsageWindow(label="Weekly", used_percent=12.5, reset_at=None),
),
details=("You have 1 reset banked - use /usage reset to activate",),
diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.py
index 6ba1911c1b1..25cca72ecb5 100644
--- a/tests/hermes_cli/test_web_server.py
+++ b/tests/hermes_cli/test_web_server.py
@@ -31,6 +31,7 @@ import hermes_cli.web_server_lifecycle as _web_server_lifecycle
import hermes_cli.web_server_memory as _web_server_memory
import hermes_cli.web_server_messaging as _web_server_messaging
import hermes_cli.web_server_sessions as _web_server_sessions
+from datetime import UTC
# ---------------------------------------------------------------------------
@@ -4184,7 +4185,7 @@ class TestGatewayUpdatedAtContract:
assert isinstance(value, str)
parsed = datetime.fromisoformat(value)
assert parsed.tzinfo is not None
- assert parsed == datetime.fromtimestamp(epoch, tz=timezone.utc)
+ assert parsed == datetime.fromtimestamp(epoch, tz=UTC)
def test_remote_health_numeric_updated_at_normalized(self, monkeypatch):
diff --git a/tests/hermes_cli/test_web_status_watchdog_surfaces.py b/tests/hermes_cli/test_web_status_watchdog_surfaces.py
index 890d6563787..502ce54eb7d 100644
--- a/tests/hermes_cli/test_web_status_watchdog_surfaces.py
+++ b/tests/hermes_cli/test_web_status_watchdog_surfaces.py
@@ -5,7 +5,7 @@
* A watchdog hard-exited the process (``degraded`` + watchdog ``exit_reason``, PID gone) -> the
retained verdict stays ``degraded`` with its ``gateway_exit_reason`` instead of a bare ``stopped``.
"""
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
import pytest
@@ -13,7 +13,7 @@ import gateway.status as _gw_status
def _iso_age(seconds_ago: float) -> str:
- return (datetime.now(timezone.utc) - timedelta(seconds=seconds_ago)).isoformat()
+ return (datetime.now(UTC) - timedelta(seconds=seconds_ago)).isoformat()
@pytest.fixture
diff --git a/tests/plugins/model_providers/test_opencode_go_profile.py b/tests/plugins/model_providers/test_opencode_go_profile.py
index 85e51bf4eef..610e3c9e72c 100644
--- a/tests/plugins/model_providers/test_opencode_go_profile.py
+++ b/tests/plugins/model_providers/test_opencode_go_profile.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import pytest
+from datetime import UTC
@pytest.fixture
@@ -308,4 +309,4 @@ def test_opencode_go_plan_windows_reach_usage_through_profile_hook(opencode_go_p
assert snapshot is not None and snapshot.provider == "opencode-go"
assert [(w.label, w.used_percent) for w in snapshot.windows] == [
("Rolling window", 3.0), ("Weekly", 2.0), ("Monthly", 2.0)]
- assert snapshot.windows[0].reset_at == datetime(2026, 9, 16, 21, 44, 55, 176000, tzinfo=timezone.utc)
+ assert snapshot.windows[0].reset_at == datetime(2026, 9, 16, 21, 44, 55, 176000, tzinfo=UTC)
diff --git a/tests/plugins/platforms/photon/test_reactions.py b/tests/plugins/platforms/photon/test_reactions.py
index 43978a92f59..b5d0101dd62 100644
--- a/tests/plugins/platforms/photon/test_reactions.py
+++ b/tests/plugins/platforms/photon/test_reactions.py
@@ -7,7 +7,7 @@ Neither path spawns the Node sidecar or binds ports.
"""
from __future__ import annotations
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Dict, List, Tuple
import pytest
@@ -63,7 +63,7 @@ def _message_event(adapter: PhotonAdapter) -> MessageEvent:
user_name=None,
),
message_id="target-msg-1",
- timestamp=datetime.now(tz=timezone.utc),
+ timestamp=datetime.now(tz=UTC),
)
diff --git a/tests/plugins/test_disk_cleanup_plugin.py b/tests/plugins/test_disk_cleanup_plugin.py
index b8582ebe3e2..f8f53aac84d 100644
--- a/tests/plugins/test_disk_cleanup_plugin.py
+++ b/tests/plugins/test_disk_cleanup_plugin.py
@@ -19,7 +19,7 @@ import os
import shutil
import sys
import tempfile
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
import pytest
@@ -278,7 +278,7 @@ class TestProtectedDirsNeverRmtreed:
old_file.write_text("x")
assert dg.guess_category(cache) is None, "the cache dir itself is never tracked"
assert dg.guess_category(old_file) == "temp", "files under cache/ still age out as temp"
- old_ts = (datetime.now(timezone.utc) - timedelta(days=8)).isoformat()
+ old_ts = (datetime.now(UTC) - timedelta(days=8)).isoformat()
dg.save_tracked([
{"path": str(cache), "category": "temp", "timestamp": old_ts, "size": 0},
{"path": str(old_file), "category": "temp", "timestamp": old_ts, "size": 1},
@@ -301,7 +301,7 @@ class TestProtectedDirsNeverRmtreed:
assert dg.guess_category(att) is None
# A stale pre-fix entry must be dropped by re-validation instead of deleted.
dg.save_tracked([{"path": str(att), "category": "test",
- "timestamp": datetime.now(timezone.utc).isoformat(), "size": 1}])
+ "timestamp": datetime.now(UTC).isoformat(), "size": 1}])
# A kanban file the call itself CREATES must not be tracked either.
new_att = att.with_name("test_new.sh")
_run_tool(pi, "write_file", {"path": str(new_att), "content": "x"},
@@ -335,7 +335,7 @@ class TestGitWorktreeFilesNeverCleaned:
f.write_text("x")
assert dg.guess_category(f) is None
dg.save_tracked([{"path": str(f), "category": "test",
- "timestamp": datetime.now(timezone.utc).isoformat(), "size": 1}])
+ "timestamp": datetime.now(UTC).isoformat(), "size": 1}])
result = dg.quick()
assert f.exists(), "git-owned test files must never be auto-deleted"
assert result["deleted"] == 0
@@ -352,7 +352,7 @@ class TestGitWorktreeFilesNeverCleaned:
scratch.write_text("x")
assert dg.guess_category(scratch) == "test"
dg.save_tracked([{"path": str(scratch), "category": "test",
- "timestamp": datetime.now(timezone.utc).isoformat(), "size": 1}])
+ "timestamp": datetime.now(UTC).isoformat(), "size": 1}])
result = dg.quick()
assert not scratch.exists()
assert result["deleted"] == 1
@@ -390,7 +390,7 @@ class TestGitWorktreeFilesNeverCleaned:
# A stale pre-fix entry is dropped by quick()'s re-validation, not deleted, while
# untracked scratch beside it in the same repo is still cleaned.
- now = datetime.now(timezone.utc).isoformat()
+ now = datetime.now(UTC).isoformat()
dg.save_tracked([{"path": str(p), "category": "test", "timestamp": now, "size": 1}
for p in (tracked, scratch)])
result = dg.quick()
@@ -482,8 +482,8 @@ class TestStaleCronEntryMigration:
run_md.write_text("x")
# Old enough to be deleted (>14 days)
- from datetime import datetime, timezone, timedelta
- old_ts = (datetime.now(timezone.utc) - timedelta(days=20)).isoformat()
+ from datetime import datetime, timedelta
+ old_ts = (datetime.now(UTC) - timedelta(days=20)).isoformat()
tracked_file = _isolate_env / "disk-cleanup" / "tracked.json"
tracked_file.parent.mkdir(parents=True, exist_ok=True)
diff --git a/tests/pm/test_network.py b/tests/pm/test_network.py
index 271ed5a28e5..1ba2c84dbad 100644
--- a/tests/pm/test_network.py
+++ b/tests/pm/test_network.py
@@ -5,7 +5,7 @@ import http.client
import socket
import ssl
import urllib.error
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from email.message import Message
from email.utils import format_datetime
@@ -70,11 +70,11 @@ def test_only_transient_failures_use_a_finite_retry_budget(error, retried):
("expired-date", 1),
])
def test_retry_after_is_bounded_and_interruptible(monkeypatch, retry_after, minimum):
- now = datetime(2020, 1, 1, tzinfo=timezone.utc).timestamp()
+ now = datetime(2020, 1, 1, tzinfo=UTC).timestamp()
monkeypatch.setattr(network.time, "time", lambda: now)
if retry_after in ("future-date", "expired-date"):
offset = 12 if retry_after == "future-date" else -12
- retry_after = format_datetime(datetime.fromtimestamp(now + offset, timezone.utc), usegmt=True)
+ retry_after = format_datetime(datetime.fromtimestamp(now + offset, UTC), usegmt=True)
error = _http_error(503, retry_after)
attempts = []
waits = []
diff --git a/tests/pm/test_runtime_bootstrap_tls.py b/tests/pm/test_runtime_bootstrap_tls.py
index 44069cae62c..4c3c561ef18 100644
--- a/tests/pm/test_runtime_bootstrap_tls.py
+++ b/tests/pm/test_runtime_bootstrap_tls.py
@@ -9,6 +9,7 @@ import subprocess
import sys
import pytest
+from datetime import UTC
@pytest.mark.platforms("posix")
@@ -100,7 +101,7 @@ def test_pm_cli_verifies_tls_with_platform_trust(tmp_path, monkeypatch):
shutil.copy2(source / "hermes_constants.py", repo / "hermes_constants.py")
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "PM test CA")])
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
cert = (x509.CertificateBuilder().subject_name(subject).issuer_name(subject)
.public_key(key.public_key()).serial_number(x509.random_serial_number())
.not_valid_before(now - timedelta(days=1)).not_valid_after(now + timedelta(days=1))
@@ -203,7 +204,7 @@ def test_cold_downloader_trusts_a_stored_intermediate_without_its_root(tmp_path)
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import NameOID
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
def issue(name, signer=None):
key = ec.generate_private_key(ec.SECP256R1())
diff --git a/tests/scripts/test_release_canary_git.py b/tests/scripts/test_release_canary_git.py
index cbb4bbe53ff..9674dfa445f 100644
--- a/tests/scripts/test_release_canary_git.py
+++ b/tests/scripts/test_release_canary_git.py
@@ -1,5 +1,5 @@
"""Canary policy on real Git refs; GitHub publication stays an inert boundary."""
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from types import SimpleNamespace
import subprocess
@@ -142,7 +142,7 @@ def test_tag_shape_and_prune_use_canonical_receipts(canary_repo, monkeypatch, ca
class Clock(datetime):
@classmethod
def now(cls, tz=None):
- return cls(2026, 8, 18, tzinfo=timezone.utc)
+ return cls(2026, 8, 18, tzinfo=UTC)
monkeypatch.setattr(release, "datetime", Clock)
release.prune_old_canaries(SimpleNamespace(remote="origin", publish=False))
diff --git a/tests/scripts/test_release_sequencer.py b/tests/scripts/test_release_sequencer.py
index 628d4eb8696..eaff203f77c 100644
--- a/tests/scripts/test_release_sequencer.py
+++ b/tests/scripts/test_release_sequencer.py
@@ -8,6 +8,7 @@ import hashlib
import json
import pytest
+from datetime import UTC
def _claims(*rows):
@@ -73,7 +74,7 @@ def test_unstarted_claim_waits_for_its_grace_period_before_burning():
from scripts.releases.sequencer import classify_runs
- claimed = datetime(2026, 9, 22, 1, 0, tzinfo=timezone.utc)
+ claimed = datetime(2026, 9, 22, 1, 0, tzinfo=UTC)
assert classify_runs([], claimed_at=claimed, now=claimed + timedelta(minutes=59)) == (
"running", None,
)
@@ -117,7 +118,7 @@ def test_the_pass_that_observes_a_failure_reruns_it_unless_burned(attempt, rerun
failed = {
"id": 42, "status": "completed", "conclusion": "failure", "run_attempt": attempt,
# Completed this instant: the pass observing the failure event.
- "updated_at": datetime.now(timezone.utc).isoformat(),
+ "updated_at": datetime.now(UTC).isoformat(),
"head_branch": "rc.1-v0.21.5", "head_sha": commit,
}
discover_run = _discover_run(tags, workflow_runs=[failed])
diff --git a/tests/scripts/test_stable_release.py b/tests/scripts/test_stable_release.py
index 1060d7df1af..b279359b206 100644
--- a/tests/scripts/test_stable_release.py
+++ b/tests/scripts/test_stable_release.py
@@ -6,7 +6,7 @@ import os
import subprocess
import sys
import zipfile
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
import pytest
@@ -30,7 +30,7 @@ def candidates(tag, commit, digest, archive=None):
manifest itself names; the payload `tag` stays plain vX.Y.Z."""
packages = []
second = 100 + int(tag.rsplit('.', 1)[1])
- release_epoch = int((datetime(2026, 8, 29, 1, 0, tzinfo=timezone.utc)
+ release_epoch = int((datetime(2026, 8, 29, 1, 0, tzinfo=UTC)
+ timedelta(seconds=second)).timestamp())
native_version = f"2026.5761.{second}.0"
ref = archive or tag
@@ -292,8 +292,8 @@ def https_origin(tmp_path, monkeypatch):
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "localhost")])
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name)
.public_key(key.public_key()).serial_number(x509.random_serial_number())
- .not_valid_before(datetime.datetime(2020, 1, 1, tzinfo=datetime.timezone.utc))
- .not_valid_after(datetime.datetime(2099, 1, 1, tzinfo=datetime.timezone.utc))
+ .not_valid_before(datetime.datetime(2020, 1, 1, tzinfo=datetime.UTC))
+ .not_valid_after(datetime.datetime(2099, 1, 1, tzinfo=datetime.UTC))
.add_extension(x509.SubjectAlternativeName([
x509.DNSName("localhost"), x509.IPAddress(ipaddress.ip_address("127.0.0.1")),
]), critical=False).sign(key, hashes.SHA256()))
diff --git a/tests/skills/test_google_workspace_api.py b/tests/skills/test_google_workspace_api.py
index 51329e3a91a..00a31aa2e1a 100644
--- a/tests/skills/test_google_workspace_api.py
+++ b/tests/skills/test_google_workspace_api.py
@@ -5,7 +5,7 @@ import json
import subprocess
import sys
import types
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
from unittest.mock import MagicMock, patch
@@ -70,7 +70,7 @@ def _write_token(path: Path, *, token="ya29.test", expiry=None, **extra):
def test_bridge_returns_valid_token(bridge_module, tmp_path):
"""Non-expired token is returned without refresh."""
- future = (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat()
+ future = (datetime.now(UTC) + timedelta(hours=1)).isoformat()
token_path = bridge_module.get_token_path()
_write_token(token_path, token="ya29.valid", expiry=future)
@@ -88,7 +88,7 @@ def test_bridge_returns_valid_token(bridge_module, tmp_path):
def test_bridge_main_injects_token_env(bridge_module, tmp_path):
"""main() sets GOOGLE_WORKSPACE_CLI_TOKEN in subprocess env."""
- future = (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat()
+ future = (datetime.now(UTC) + timedelta(hours=1)).isoformat()
token_path = bridge_module.get_token_path()
_write_token(token_path, token="ya29.injected", expiry=future)
diff --git a/tests/skills/test_memento_cards.py b/tests/skills/test_memento_cards.py
index 9aeb053b743..820db6437d2 100644
--- a/tests/skills/test_memento_cards.py
+++ b/tests/skills/test_memento_cards.py
@@ -4,7 +4,7 @@ import csv
import json
import sys
import uuid
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
from unittest import mock
@@ -108,9 +108,9 @@ class TestRating:
def test_hard_adds_1_day(self, capsys):
_run(capsys, ["add", "--question", "Q", "--answer", "A"])
card_id = _run(capsys, ["list"])["cards"][0]["id"]
- before = datetime.now(timezone.utc)
+ before = datetime.now(UTC)
result = _run(capsys, ["rate", "--id", card_id, "--rating", "hard"])
- after = datetime.now(timezone.utc)
+ after = datetime.now(UTC)
next_review = datetime.fromisoformat(result["card"]["next_review_at"])
assert before + timedelta(days=1) <= next_review <= after + timedelta(days=1)
assert result["card"]["ease_streak"] == 0
@@ -118,7 +118,7 @@ class TestRating:
def test_good_adds_3_days(self, capsys):
_run(capsys, ["add", "--question", "Q", "--answer", "A"])
card_id = _run(capsys, ["list"])["cards"][0]["id"]
- before = datetime.now(timezone.utc)
+ before = datetime.now(UTC)
result = _run(capsys, ["rate", "--id", card_id, "--rating", "good"])
next_review = datetime.fromisoformat(result["card"]["next_review_at"])
assert next_review >= before + timedelta(days=3)
diff --git a/tests/skills/test_skill_blueprint_contracts.py b/tests/skills/test_skill_blueprint_contracts.py
index 8bc24822942..a964cde17a5 100644
--- a/tests/skills/test_skill_blueprint_contracts.py
+++ b/tests/skills/test_skill_blueprint_contracts.py
@@ -1,5 +1,5 @@
"""Blueprint-to-skill relationships, independent of the generic catalog/renderer tests."""
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
import pytest
@@ -54,7 +54,7 @@ def test_price_watch_fills_and_persists_with_chosen_cadence(hours, tmp_path, mon
assert saved["deliver"] == "local"
for text in ("https://example.test/widget", "below 42 credits", "[SILENT]"):
assert text in saved["prompt"], text
- ticks = croniter(saved["schedule"]["expr"], datetime(2026, 1, 1, tzinfo=timezone.utc))
+ ticks = croniter(saved["schedule"]["expr"], datetime(2026, 1, 1, tzinfo=UTC))
# Span a day boundary: wrong-field steps can otherwise look valid once.
times = [ticks.get_next(datetime) for _ in range(26)]
assert {b - a for a, b in itertools.pairwise(times)} == {timedelta(hours=int(hours))}
diff --git a/tests/tools/test_docker_environment.py b/tests/tools/test_docker_environment.py
index d9f859084b6..442393b9ce5 100644
--- a/tests/tools/test_docker_environment.py
+++ b/tests/tools/test_docker_environment.py
@@ -1453,7 +1453,7 @@ def test_cleanup_on_env_with_no_container_id_does_not_raise(monkeypatch):
def _now_iso(offset_seconds: int = 0) -> str:
"""Return an RFC3339 timestamp ``offset_seconds`` in the past."""
import datetime
- t = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(seconds=offset_seconds)
+ t = datetime.datetime.now(datetime.UTC) - datetime.timedelta(seconds=offset_seconds)
# Format like Docker emits — with nanoseconds-style trailing digits.
return t.isoformat().replace("+00:00", ".123456789Z")
@@ -1559,7 +1559,7 @@ def test_container_finished_at_parses_nanosecond_timestamp(monkeypatch):
result = docker_env._container_finished_at("/usr/bin/docker", "test-cid")
assert result is not None, "must parse RFC3339 with nanoseconds"
import datetime
- assert result.tzinfo == datetime.timezone.utc
+ assert result.tzinfo == datetime.UTC
assert result.year == 2026 and result.month == 5 and result.day == 28
diff --git a/tests/tools/test_managed_tool_gateway.py b/tests/tools/test_managed_tool_gateway.py
index 1f96ed1c8ba..ddce2ed5680 100644
--- a/tests/tools/test_managed_tool_gateway.py
+++ b/tests/tools/test_managed_tool_gateway.py
@@ -1,6 +1,6 @@
import os
import json
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timedelta, timezone, UTC
from importlib.util import module_from_spec, spec_from_file_location
from pathlib import Path
import sys
@@ -85,7 +85,7 @@ def test_resolve_managed_tool_gateway_is_disabled_without_subscription():
def test_read_nous_access_token_refreshes_expiring_cached_token(tmp_path, monkeypatch):
monkeypatch.delenv("TOOL_GATEWAY_USER_TOKEN", raising=False)
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- expires_at = (datetime.now(timezone.utc) + timedelta(seconds=30)).isoformat()
+ expires_at = (datetime.now(UTC) + timedelta(seconds=30)).isoformat()
(tmp_path / "auth.json").write_text(json.dumps({
"providers": {
"nous": {
@@ -106,7 +106,7 @@ def test_read_nous_access_token_refreshes_expiring_cached_token(tmp_path, monkey
def test_is_managed_tool_gateway_ready_skips_refresh_for_expired_cached_token(tmp_path, monkeypatch):
monkeypatch.delenv("TOOL_GATEWAY_USER_TOKEN", raising=False)
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- expired_at = (datetime.now(timezone.utc) - timedelta(seconds=30)).isoformat()
+ expired_at = (datetime.now(UTC) - timedelta(seconds=30)).isoformat()
(tmp_path / "auth.json").write_text(json.dumps({
"providers": {
"nous": {
diff --git a/tests/tools/test_session_search.py b/tests/tools/test_session_search.py
index 033e727e3ef..307574c3da6 100644
--- a/tests/tools/test_session_search.py
+++ b/tests/tools/test_session_search.py
@@ -10,7 +10,7 @@ All run zero LLM calls.
"""
import json
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
import pytest
@@ -1120,7 +1120,7 @@ class TestNewResetLineageBrowse:
def _unix(year, month, day):
- return int(datetime(year, month, day, tzinfo=timezone.utc).timestamp())
+ return int(datetime(year, month, day, tzinfo=UTC).timestamp())
def _set_started(db, **started_at_by_sid):
diff --git a/tests/tui_gateway/test_session_usage_account_lines.py b/tests/tui_gateway/test_session_usage_account_lines.py
index 50290a2a261..e9d19461e78 100644
--- a/tests/tui_gateway/test_session_usage_account_lines.py
+++ b/tests/tui_gateway/test_session_usage_account_lines.py
@@ -4,7 +4,7 @@ The CLI/TUI slash worker and gateway ``/usage`` render Codex quota windows via
``render_account_usage_lines``; the Desktop feed reads ``session.usage`` instead, so the RPC
must ship the same lines (``account_lines``) or that surface silently omits them.
"""
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from types import SimpleNamespace
from unittest.mock import patch
@@ -13,7 +13,7 @@ from agent.account_usage import AccountUsageSnapshot, AccountUsageWindow
def _codex_snapshot() -> AccountUsageSnapshot:
return AccountUsageSnapshot(
- provider="openai-codex", source="usage_api", fetched_at=datetime.now(timezone.utc), plan="Plus",
+ provider="openai-codex", source="usage_api", fetched_at=datetime.now(UTC), plan="Plus",
windows=(AccountUsageWindow(label="Weekly", used_percent=12.0),),
)
diff --git a/tools/browser_tool_lifecycle.py b/tools/browser_tool_lifecycle.py
index 34807c2c9cd..a530ea30e47 100644
--- a/tools/browser_tool_lifecycle.py
+++ b/tools/browser_tool_lifecycle.py
@@ -10,7 +10,7 @@ import signal
import subprocess
import threading
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Dict, Optional, Tuple
@@ -41,7 +41,7 @@ def _session_expiry_timestamp(session_info: dict[str, Any]) -> Optional[float]:
_bt.logger.warning("Ignoring invalid cloud browser session expiry timestamp")
return None
if parsed.tzinfo is None:
- parsed = parsed.replace(tzinfo=timezone.utc)
+ parsed = parsed.replace(tzinfo=UTC)
return parsed.timestamp()
diff --git a/tools/environments/docker.py b/tools/environments/docker.py
index 1a4545677dc..414c275d3ae 100644
--- a/tools/environments/docker.py
+++ b/tools/environments/docker.py
@@ -195,7 +195,7 @@ def reap_orphan_containers(
return 0
# Per-container inspect keeps the failure blast radius to one container.
- now = datetime.datetime.now(datetime.timezone.utc)
+ now = datetime.datetime.now(datetime.UTC)
removed = 0
for cid in (ln.strip() for ln in listing.stdout.splitlines() if ln.strip()):
finished_at = _container_finished_at(docker, cid)
diff --git a/tools/managed_tool_gateway.py b/tools/managed_tool_gateway.py
index 2649f62fea9..f767f44c958 100644
--- a/tools/managed_tool_gateway.py
+++ b/tools/managed_tool_gateway.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import json
import logging
import os
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from dataclasses import dataclass
from typing import Callable, Optional
@@ -69,12 +69,12 @@ def _parse_timestamp(value: object) -> Optional[datetime]:
parsed = datetime.fromisoformat(normalized[:-1] + "+00:00" if normalized.endswith("Z") else normalized)
except ValueError:
return None
- return (parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=timezone.utc)).astimezone(timezone.utc)
+ return (parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)).astimezone(UTC)
def _access_token_is_expiring(expires_at: object, skew_seconds: int) -> bool:
expires = _parse_timestamp(expires_at)
- return expires is None or (expires - datetime.now(timezone.utc)).total_seconds() <= max(0, int(skew_seconds))
+ return expires is None or (expires - datetime.now(UTC)).total_seconds() <= max(0, int(skew_seconds))
def _read_user_token_override() -> Optional[str]:
diff --git a/tools/plugin_guard.py b/tools/plugin_guard.py
index b1a091f81c1..8dc57c069de 100644
--- a/tools/plugin_guard.py
+++ b/tools/plugin_guard.py
@@ -11,7 +11,7 @@ needs confirmation, ``dangerous`` is blocked and ``--force`` does NOT override.
from __future__ import annotations
import ast
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Iterator, List, Optional, Tuple
@@ -342,7 +342,7 @@ def scan_plugin(plugin_dir: Path, source: str = "") -> ScanResult:
summary = f"{plugin_dir.name}: clean scan, no threats detected"
result = ScanResult(
skill_name=plugin_dir.name, source=source or plugin_dir.name, trust_level="community",
- verdict=verdict, findings=all_findings, scanned_at=datetime.now(timezone.utc).isoformat(),
+ verdict=verdict, findings=all_findings, scanned_at=datetime.now(UTC).isoformat(),
summary=summary)
result.scan_provenance = {
"scanner_version": PLUGIN_SCANNER_VERSION, "verdict": verdict, "source": result.source}
diff --git a/tools/session_search_tool.py b/tools/session_search_tool.py
index 5229e4f97d6..8e0db86829a 100644
--- a/tools/session_search_tool.py
+++ b/tools/session_search_tool.py
@@ -12,7 +12,7 @@ import json
import logging
import re
import time
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from typing import Any, Dict, List, Optional, Union
from hermes_state_common import _BOUNDARY_END_REASONS
@@ -146,7 +146,7 @@ def _parse_iso_bound(value: Optional[str]) -> Optional[int]:
raise ValueError(f"invalid time bound: {value!r} (expected ISO date/datetime like "
"2026-07-01, or a relative duration like 7d, 24h, 2w)") from None
if parsed.tzinfo is None:
- parsed = parsed.replace(tzinfo=timezone.utc)
+ parsed = parsed.replace(tzinfo=UTC)
return int(parsed.timestamp())
diff --git a/tools/skill_ledger.py b/tools/skill_ledger.py
index 2c70bb75f18..dc983d18771 100644
--- a/tools/skill_ledger.py
+++ b/tools/skill_ledger.py
@@ -20,7 +20,7 @@ import re
import tarfile
import time as _time
import uuid
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
@@ -307,7 +307,7 @@ def append_entry(
if action != "pre-rollback":
before, after = _delta(before or [], after or [])
entry = {
- "id": uuid.uuid4().hex[:12], "ts": datetime.now(timezone.utc).isoformat(),
+ "id": uuid.uuid4().hex[:12], "ts": datetime.now(UTC).isoformat(),
"actor": actor if actor in _VALID_ACTORS else derive_actor(),
"action": action, "skill": skill, "evidence": evidence or {},
"before": before or [], "after": after or []}
diff --git a/tools/skill_usage.py b/tools/skill_usage.py
index eefee23a6ce..0eab4f685fe 100644
--- a/tools/skill_usage.py
+++ b/tools/skill_usage.py
@@ -12,7 +12,7 @@ import logging
import os
import threading
from contextlib import contextmanager, suppress
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Set, Tuple
@@ -109,7 +109,7 @@ def _read_lines(path: Path, fail_log: str) -> list[str]:
def _now_iso() -> str:
- return datetime.now(timezone.utc).isoformat()
+ return datetime.now(UTC).isoformat()
def _parse_iso_timestamp(value: Any) -> Optional[datetime]:
@@ -117,7 +117,7 @@ def _parse_iso_timestamp(value: Any) -> Optional[datetime]:
parsed = datetime.fromisoformat(str(value)) if value else None
except (TypeError, ValueError):
return None
- return parsed.replace(tzinfo=timezone.utc) if parsed and parsed.tzinfo is None else parsed
+ return parsed.replace(tzinfo=UTC) if parsed and parsed.tzinfo is None else parsed
def latest_activity_at(record: dict[str, Any]) -> Optional[str]:
@@ -638,7 +638,7 @@ def archive_skill(skill_name: str) -> tuple[bool, str]:
except OSError as e:
return False, f"failed to create archive dir: {e}"
if dest.exists():
- dest = dest.with_name(f"{skill_dir.name}-{datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S')}")
+ dest = dest.with_name(f"{skill_dir.name}-{datetime.now(UTC).strftime('%Y%m%d%H%M%S')}")
# complete_package: consolidation may have re-homed support files first, so a disk-only capture can come
# back hollow; the fill from the newest curator backup keeps rollback restorable.
return _relocate(skill_dir, dest, skill_name, "archive", complete_package=True, skill=skill_name)
diff --git a/tools/skills_guard.py b/tools/skills_guard.py
index b1e797219a4..3c980d7d62e 100644
--- a/tools/skills_guard.py
+++ b/tools/skills_guard.py
@@ -13,7 +13,7 @@ import hashlib
import json
from contextlib import suppress
from dataclasses import asdict, dataclass, field
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import List, Tuple
@@ -662,7 +662,7 @@ def scan_skill(skill_path: Path, source: str = "community") -> ScanResult:
elif skill_path.is_file():
findings.extend(scan_file(skill_path, skill_path.name))
verdict = _determine_verdict(findings)
- return ScanResult(name, source, trust, verdict, findings, datetime.now(timezone.utc).isoformat(),
+ return ScanResult(name, source, trust, verdict, findings, datetime.now(UTC).isoformat(),
_build_summary(name, source, trust, verdict, findings))
diff --git a/tools/skills_hub.py b/tools/skills_hub.py
index 524d82293f5..b4787fb268b 100644
--- a/tools/skills_hub.py
+++ b/tools/skills_hub.py
@@ -16,7 +16,7 @@ import logging
import time
from contextvars import ContextVar
from contextlib import ExitStack, contextmanager
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional
from urllib.parse import urljoin
@@ -322,7 +322,7 @@ class HubLockFile(_JsonStateFile):
safe_name = _validate_skill_name(name)
safe_install_path = _normalize_lock_install_path(install_path, safe_name)
data = self.load()
- now = datetime.now(timezone.utc).isoformat()
+ now = datetime.now(UTC).isoformat()
data["installed"][safe_name] = {
"source": source,
"identifier": identifier,
@@ -388,7 +388,7 @@ def append_audit_log(action: str, skill_name: str, source: str,
"""Append one space-separated line to the audit log (best-effort)."""
audit_log = _audit_log()
audit_log.parent.mkdir(parents=True, exist_ok=True)
- timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+ timestamp = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
parts = [timestamp, action, skill_name, f"{source}:{trust_level}", verdict]
if extra:
parts.append(extra)
diff --git a/tools/skills_sync_optional.py b/tools/skills_sync_optional.py
index 5851e2b2351..ffb62876e34 100644
--- a/tools/skills_sync_optional.py
+++ b/tools/skills_sync_optional.py
@@ -4,7 +4,7 @@ patchable helpers resolve through ``_ss()`` at call time so ``tools.skills_sync`
import json
import logging
from contextlib import suppress
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path, PurePosixPath
from typing import Dict, Iterator, List, Optional, Set, Tuple
@@ -140,7 +140,7 @@ def restore_official_optional_skill(name: str, *, restore: bool = False) -> dict
return {"ok": False, "message": message, "restored": [], "backfilled": [], "backed_up": []}
restored: list[str] = []
backed_up: list[str] = []
- timestamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
+ timestamp = datetime.now(UTC).strftime("%Y%m%d-%H%M%S")
backup_root = ss._skills_dir() / ".restore-backups" / f"official-optional-{timestamp}"
for folder_name, install_path, src in targets if restore else []:
dest = ss._skills_dir() / Path(*install_path.split("/"))
@@ -218,7 +218,7 @@ def _backfill_optional_provenance(quiet: bool = False) -> list[str]:
dest, install_path = found # still requires a byte-identical hash below
if install_path in existing_paths or ss._dir_hash(dest) != ss._dir_hash(src):
continue
- timestamp = datetime.now(timezone.utc).isoformat()
+ timestamp = datetime.now(UTC).isoformat()
installed[lock_name] = {
"source": "official", "identifier": f"official/{install_path}",
"trust_level": "builtin", "scan_verdict": "backfilled",
diff --git a/tools/x_search_tool.py b/tools/x_search_tool.py
index c24a0caa660..577cc2f3d08 100644
--- a/tools/x_search_tool.py
+++ b/tools/x_search_tool.py
@@ -14,7 +14,7 @@ from __future__ import annotations
import json
import logging
import time
-from datetime import date, datetime, timezone
+from datetime import date, datetime, timezone, UTC
from typing import Any, Dict, List, Optional, Tuple
import requests
@@ -106,7 +106,7 @@ def _validate_date_range(from_date: str, to_date: str) -> None:
raise ValueError(
f"from_date ({parsed_from.isoformat()}) must be on or before to_date ({parsed_to.isoformat()})"
)
- today_utc = datetime.now(timezone.utc).date()
+ today_utc = datetime.now(UTC).date()
if parsed_from is not None and parsed_from > today_utc:
raise ValueError(
f"from_date ({parsed_from.isoformat()}) is in the future; "
diff --git a/website/scripts/extract-plugins.py b/website/scripts/extract-plugins.py
index a751462f9e8..49bc6d311a3 100644
--- a/website/scripts/extract-plugins.py
+++ b/website/scripts/extract-plugins.py
@@ -31,7 +31,7 @@ import re
import subprocess
import sys
from collections import Counter
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
from urllib.parse import urlsplit
@@ -335,7 +335,7 @@ def main(catalog_dir: Path = DEFAULT_CATALOG_DIR, output_dir: Path = DEFAULT_OUT
by_tier = Counter(e["tier"] for e in entries)
by_category = Counter(e["category"] for e in entries)
meta = {
- "generatedAt": datetime.now(timezone.utc).isoformat(),
+ "generatedAt": datetime.now(UTC).isoformat(),
"total": len(entries),
"byTier": {tier: by_tier.get(tier, 0) for tier in CATALOG_TIERS},
"byCategory": {c: by_category.get(c, 0) for c in CATALOG_CATEGORIES if by_category.get(c)},
diff --git a/website/scripts/extract-skills.py b/website/scripts/extract-skills.py
index ecadfc7581e..bd483a2afd3 100644
--- a/website/scripts/extract-skills.py
+++ b/website/scripts/extract-skills.py
@@ -22,7 +22,7 @@ import json
import os
import sys
from collections import Counter
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, REPO_ROOT)
@@ -666,7 +666,7 @@ def main():
# without changing the shape of skills.json.
by_source = Counter(s["source"] for s in all_skills)
meta = {
- "extractedAt": datetime.now(timezone.utc).isoformat(),
+ "extractedAt": datetime.now(UTC).isoformat(),
"totalSkills": len(all_skills),
"localSkills": len(local),
"externalSkills": len(external),
diff --git a/website/scripts/fetch-plugin-stars.py b/website/scripts/fetch-plugin-stars.py
index 39445483e16..d63fdfe1d14 100644
--- a/website/scripts/fetch-plugin-stars.py
+++ b/website/scripts/fetch-plugin-stars.py
@@ -28,7 +28,7 @@ import re
import sys
import urllib.error
import urllib.request
-from datetime import datetime, timezone
+from datetime import datetime, timezone, UTC
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[2]
@@ -162,7 +162,7 @@ def main(catalog_dir: Path = DEFAULT_CATALOG_DIR, output: Path = DEFAULT_OUTPUT,
slugs = catalog_slugs(catalog_dir)
prev_stars = {k: int(v) for k, v in (previous.get("stars") or {}).items() if isinstance(v, (int, float))}
stars, probed = probe_stars(slugs, prev_stars, token or os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN"))
- fetched_at = datetime.now(timezone.utc).isoformat() if probed else previous.get("fetched_at")
+ fetched_at = datetime.now(UTC).isoformat() if probed else previous.get("fetched_at")
output.write_text(json.dumps({"fetched_at": fetched_at, "stars": stars}, separators=(",", ":")),
encoding="utf-8")
if not probed: