Repository: getmoto/moto

Issue:
Question:  freeze_time() not working as expected in sagemaker unit test
When replacing the usage of "sure" with regular assertions, I noticed one test failing in code that I did not alter:
```
=================================== FAILURES ===================================
________________ test_list_model_packages_creation_time_before _________________

    @mock_sagemaker
    def test_list_model_packages_creation_time_before():
        if settings.TEST_SERVER_MODE:
            raise SkipTest("Can't freeze time in ServerMode")
        client = boto3.client("sagemaker", region_name="eu-west-1")
        with freeze_time("2020-01-01 00:00:00"):
            client.create_model_package(
                ModelPackageName="test-model-package",
                ModelPackageDescription="test-model-package-description",
            )
        with freeze_time("2021-01-01 00:00:00"):
            client.create_model_package(
                ModelPackageName="test-model-package-2",
                ModelPackageDescription="test-model-package-description-2",
            )
        resp = client.list_model_packages(CreationTimeBefore="2020-01-01T02:00:00Z")

>       assert len(resp["ModelPackageSummaryList"]) == 1
E       assert 0 == 1
E        +  where 0 = len([])

tests/test_sagemaker/test_sagemaker_model_packages.py:62: AssertionError
=========================== short test summary info ============================
FAILED tests/test_sagemaker/test_sagemaker_model_packages.py::test_list_model_packages_creation_time_before - assert 0 == 1
```

When I set a breakpoint in `list_model_packages()` and looked at the date of the first package, it showed the current time, not the frozen time:

```
(Pdb) pprint(self.model_packages['arn:aws:sagemaker:eu-west-1:123456789012:model-package/test-model-package'].__dict__)
{'additional_inference_specifications': None,
 'approval_description': None,
 'certify_for_marketplace': None,
 'client_token': '7a20e3b1-df5e-422e-9b9c-d12f68cb89d0',
 'created_by': {'DomainId': 'fake-domain-id',
                'UserProfileArn': 'arn:aws:sagemaker:eu-west-1:123456789012:user-profile/fake-domain-id/fake-user-profile-name',
                'UserProfileName': 'fake-user-profile-name'},
 'creation_time': datetime.datetime(2023, 8, 8, 6, 22, 55, 585132),
 'customer_metadata_properties': None,
 'domain': None,
 'drift_check_baselines': None,
 'inference_specification': None,
 'last_modified_by': {'DomainId': 'fake-domain-id',
                      'UserProfileArn': 'arn:aws:sagemaker:eu-west-1:123456789012:user-profile/fake-domain-id/fake-user-profile-name',
                      'UserProfileName': 'fake-user-profile-name'},
 'last_modified_time': datetime.datetime(2023, 8, 8, 6, 22, 55, 585132),
 'metadata_properties': None,
 'model_approval_status': None,
 'model_metrics': None,
 'model_package_arn': 'arn:aws:sagemaker:eu-west-1:123456789012:model-package/test-model-package',
 'model_package_description': 'test-model-package-description',
 'model_package_group_name': None,
 'model_package_name': 'test-model-package',
 'model_package_status': 'Completed',
 'model_package_status_details': ({'ImageScanStatuses': [{'Name': 'arn:aws:sagemaker:eu-west-1:123456789012:model-package/test-model-package',
                                                          'Status': 'Completed'}],
                                   'ValidationStatuses': [{'Name': 'arn:aws:sagemaker:eu-west-1:123456789012:model-package/test-model-package',
                                                           'Status': 'Completed'}]},),
 'model_package_version': None,
 'sample_payload_url': None,
 'source_algorithm_specification': None,
 'tags': None,
 'task': None,
 'validation_specification': None}
```

This test passes in the GitHub workflow, so I'm wondering if some special setup is needed to run this test.


Discussion:
Hey @kbalk, these tests don't need any setup - I have honestly no idea why it would show the current time.

When I read the title, I assumed it was a UTC issue, because I have seen time comparisons be off by a few hours - see https://github.com/getmoto/moto/pull/5039 for example. But never anything like this.

Resolving patch:
diff --git a/moto/sagemaker/models.py b/moto/sagemaker/models.py
--- a/moto/sagemaker/models.py
+++ b/moto/sagemaker/models.py
@@ -3,6 +3,7 @@
 import random
 import string
 from datetime import datetime
+from dateutil.tz import tzutc
 from typing import Any, Dict, List, Optional, Iterable, Union
 
 from moto.core import BaseBackend, BackendDict, BaseModel, CloudFormationModel
@@ -994,7 +995,7 @@ def __init__(
             _type="model-package",
             _id=model_package_name,
         )
-        datetime_now = datetime.utcnow()
+        datetime_now = datetime.now(tzutc())
         self.model_package_name = model_package_name
         self.model_package_group_name = model_package_group_name
         self.model_package_version = model_package_version
@@ -2868,9 +2869,13 @@ def list_model_packages(  # type: ignore[misc]
         sort_order: Optional[str],
     ) -> List[ModelPackage]:
         if isinstance(creation_time_before, int):
-            creation_time_before_datetime = datetime.fromtimestamp(creation_time_before)
+            creation_time_before_datetime = datetime.fromtimestamp(
+                creation_time_before, tz=tzutc()
+            )
         if isinstance(creation_time_after, int):
-            creation_time_after_datetime = datetime.fromtimestamp(creation_time_after)
+            creation_time_after_datetime = datetime.fromtimestamp(
+                creation_time_after, tz=tzutc()
+            )
         if model_package_group_name is not None:
             model_package_type = "Versioned"
         model_package_summary_list = list(


Test patch: