From 64da7f853bd79d4cb8a9cefdf9b412b897a4f1cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafa=C5=82=20Pito=C5=84?= Date: Tue, 20 Feb 2024 17:25:42 +0100 Subject: [PATCH] Fix `datetime.utcnow` deprecation warnings (#1162) --- ariadne/contrib/tracing/apollotracing.py | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/ariadne/contrib/tracing/apollotracing.py b/ariadne/contrib/tracing/apollotracing.py index 217cebef8..e803b8c39 100644 --- a/ariadne/contrib/tracing/apollotracing.py +++ b/ariadne/contrib/tracing/apollotracing.py @@ -1,4 +1,3 @@ -from datetime import datetime from inspect import iscoroutinefunction from typing import Any, List, Optional, cast @@ -20,6 +19,19 @@ def perf_counter_ns() -> int: return int(perf_counter() * NS_IN_SECOND) +try: + from datetime import UTC, datetime # type: ignore[attr-defined] + + def utc_now(): + return datetime.now(UTC) + +except ImportError: + from datetime import datetime + + def utc_now(): + return datetime.utcnow() + + TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" @@ -33,7 +45,7 @@ def __init__(self, trace_default_resolver: bool = False) -> None: self._totals = None def request_started(self, context: ContextValue): - self.start_date = datetime.utcnow() + self.start_date = utc_now() self.start_timestamp = perf_counter_ns() def resolve(self, next_: Resolver, obj: Any, info: GraphQLResolveInfo, **kwargs): @@ -93,7 +105,7 @@ def get_totals(self): def _get_totals(self): return { "start": self.start_date, - "end": datetime.utcnow(), + "end": utc_now(), "duration": perf_counter_ns() - self.start_timestamp, "resolvers": self.resolvers, }