Skip to content

Commit

Permalink
Techdebt: Replace deprecated utcfromtimestamp-methods (#7146)
Browse files Browse the repository at this point in the history
  • Loading branch information
bblommers authored Dec 20, 2023
1 parent be0dffc commit d77acd4
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 13 deletions.
7 changes: 2 additions & 5 deletions moto/core/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
gzip_decompress,
method_names_from_class,
params_sort_function,
utcfromtimestamp,
)
from moto.utilities.utils import load_resource, load_resource_as_bytes

Expand Down Expand Up @@ -1076,11 +1077,7 @@ def to_str(value: Any, spec: Dict[str, Any]) -> str:
elif vtype == "double":
return str(value)
elif vtype == "timestamp":
return (
datetime.datetime.utcfromtimestamp(value)
.replace(tzinfo=datetime.timezone.utc)
.isoformat()
)
return utcfromtimestamp(value).replace(tzinfo=datetime.timezone.utc).isoformat()
elif vtype == "string":
return str(value)
elif value is None:
Expand Down
22 changes: 20 additions & 2 deletions moto/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ def str_to_rfc_1123_datetime(value: str) -> datetime.datetime:

def unix_time(dt: Optional[datetime.datetime] = None) -> float:
dt = dt or utcnow()
epoch = datetime.datetime.utcfromtimestamp(0)
epoch = utcfromtimestamp(0)
delta = dt - epoch
return (delta.days * 86400) + (delta.seconds + (delta.microseconds / 1e6))

Expand All @@ -191,14 +191,32 @@ def unix_time_millis(dt: Optional[datetime.datetime] = None) -> float:
return unix_time(dt) * 1000.0


def utcfromtimestamp(value: int) -> datetime.datetime:
"""
Return the UTC datetime corresponding to the POSIX timestamp, with tzinfo None. The resulting object is naive.
"""
# Python 3.12 starts throwing deprecation warnings for utcfromtimestamp()
# The docs recommend to use fromtimestamp(UTC) instead
#
# fromtimestamp(UTC) creates an aware datetime - but utcfromtimestamp() creates a naive datetime
# That's why we have to `replace(tzinfo=None)` to make now(UTC) naive.
if PYTHON_311:
# Only available from 3.11
from datetime import UTC # type: ignore

return datetime.datetime.fromtimestamp(value, tz=UTC).replace(tzinfo=None)
else:
return datetime.datetime.utcfromtimestamp(value)


def utcnow() -> datetime.datetime:
# Python 3.12 starts throwing deprecation warnings for utcnow()
# The docs recommend to use now(UTC) instead
#
# now(UTC) creates an aware datetime - but utcnow() creates a naive datetime
# That's why we have to `replace(tzinfo=None)` to make now(UTC) naive.
if PYTHON_311:
# Only available in 3.11
# Only available from 3.11
from datetime import UTC # type: ignore

return datetime.datetime.now(UTC).replace(tzinfo=None)
Expand Down
6 changes: 3 additions & 3 deletions moto/events/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import sys
import warnings
from collections import OrderedDict
from datetime import datetime
from enum import Enum, unique
from json import JSONDecodeError
from operator import eq, ge, gt, le, lt
Expand All @@ -20,6 +19,7 @@
iso_8601_datetime_without_milliseconds,
unix_time,
unix_time_millis,
utcfromtimestamp,
)
from moto.events.exceptions import (
IllegalStatusException,
Expand Down Expand Up @@ -170,7 +170,7 @@ def _send_to_cw_log_group(self, name: str, event: Dict[str, Any]) -> None:

event_copy = copy.deepcopy(event)
event_copy["time"] = iso_8601_datetime_without_milliseconds(
datetime.utcfromtimestamp(event_copy["time"])
utcfromtimestamp(event_copy["time"])
)

log_stream_name = str(random.uuid4())
Expand Down Expand Up @@ -202,7 +202,7 @@ def _send_to_sqs_queue(

event_copy = copy.deepcopy(event)
event_copy["time"] = iso_8601_datetime_without_milliseconds(
datetime.utcfromtimestamp(event_copy["time"])
utcfromtimestamp(event_copy["time"])
)

if group_id:
Expand Down
4 changes: 2 additions & 2 deletions moto/secretsmanager/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from typing import Any, Dict, List, Optional, Tuple

from moto.core import BackendDict, BaseBackend, BaseModel
from moto.core.utils import utcnow
from moto.core.utils import utcfromtimestamp, utcnow
from moto.moto_api._internal import mock_random

from .exceptions import (
Expand Down Expand Up @@ -273,7 +273,7 @@ def _is_valid_identifier(self, identifier: str) -> bool:
return identifier in self.secrets

def _unix_time_secs(self, dt: datetime.datetime) -> float:
epoch = datetime.datetime.utcfromtimestamp(0)
epoch = utcfromtimestamp(0)
return (dt - epoch).total_seconds()

def _client_request_token_validator(self, client_request_token: str) -> None:
Expand Down
3 changes: 2 additions & 1 deletion tests/test_cloudwatch/test_cloudwatch_boto3.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

from moto import mock_cloudwatch, mock_s3
from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID
from moto.core.utils import utcnow


@mock_cloudwatch
Expand Down Expand Up @@ -1912,7 +1913,7 @@ def test_get_metric_data_queries():
verify that >= 10 queries can still be parsed
there was an error with the order of parsing items, leading to IndexError
"""
now = datetime.utcnow().replace(microsecond=0)
now = utcnow().replace(microsecond=0)
start_time = now - timedelta(minutes=10)
end_time = now + timedelta(minutes=5)
original_query = {
Expand Down

0 comments on commit d77acd4

Please sign in to comment.