diff --git a/cloudinit/sources/DataSourceGCE.py b/cloudinit/sources/DataSourceGCE.py index 949580d8bce..8054d6f178f 100644 --- a/cloudinit/sources/DataSourceGCE.py +++ b/cloudinit/sources/DataSourceGCE.py @@ -213,14 +213,14 @@ def _has_expired(public_key): return False expire_str = json_obj["expireOn"] - format_str = "%Y-%m-%dT%H:%M:%S+0000" + format_str = "%Y-%m-%dT%H:%M:%S%z" try: expire_time = datetime.datetime.strptime(expire_str, format_str) except ValueError: return False # Expire the key if and only if we have exceeded the expiration timestamp. - return datetime.datetime.utcnow() > expire_time + return datetime.datetime.now(datetime.timezone.utc) > expire_time def _parse_public_keys(public_keys_data, default_user=None): diff --git a/cloudinit/sources/azure/errors.py b/cloudinit/sources/azure/errors.py index 53373ce5c89..a7ed043e184 100644 --- a/cloudinit/sources/azure/errors.py +++ b/cloudinit/sources/azure/errors.py @@ -6,7 +6,7 @@ import csv import logging import traceback -from datetime import datetime +from datetime import datetime, timezone from io import StringIO from typing import Any, Dict, List, Optional, Tuple from xml.etree import ElementTree as ET # nosec B405 @@ -52,7 +52,7 @@ def __init__( else: self.supporting_data = {} - self.timestamp = datetime.utcnow() + self.timestamp = datetime.now(timezone.utc) try: self.vm_id = identity.query_vm_id() diff --git a/cloudinit/sources/azure/kvp.py b/cloudinit/sources/azure/kvp.py index 735c4616be1..903b812259f 100644 --- a/cloudinit/sources/azure/kvp.py +++ b/cloudinit/sources/azure/kvp.py @@ -3,7 +3,7 @@ # This file is part of cloud-init. See LICENSE file for license information. import logging -from datetime import datetime +from datetime import datetime, timezone from typing import Optional from cloudinit import version @@ -49,7 +49,7 @@ def report_success_to_host() -> bool: [ "result=success", f"agent=Cloud-Init/{version.version_string()}", - f"timestamp={datetime.utcnow().isoformat()}", + f"timestamp={datetime.now(timezone.utc).isoformat()}", f"vm_id={vm_id}", ] ) diff --git a/tests/integration_tests/clouds.py b/tests/integration_tests/clouds.py index 345d1545887..48e55e1d655 100644 --- a/tests/integration_tests/clouds.py +++ b/tests/integration_tests/clouds.py @@ -330,7 +330,7 @@ def _perform_launch( except KeyError: profile_list = self._get_or_set_profile_list(release) - prefix = datetime.datetime.utcnow().strftime("cloudinit-%m%d-%H%M%S") + prefix = datetime.datetime.now(timezone.utc).strftime("cloudinit-%m%d-%H%M%S") default_name = prefix + "".join( random.choices(string.ascii_lowercase + string.digits, k=8) ) diff --git a/tests/integration_tests/test_paths.py b/tests/integration_tests/test_paths.py index d9608da49d0..e91bd764604 100644 --- a/tests/integration_tests/test_paths.py +++ b/tests/integration_tests/test_paths.py @@ -66,7 +66,7 @@ def collect_logs(self, custom_client: IntegrationInstance): found_logs = custom_client.execute( "tar -tf cloud-init.tar.gz" ).stdout.splitlines() - dirname = datetime.utcnow().date().strftime("cloud-init-logs-%Y-%m-%d") + dirname = datetime.now(timezone.utc).date().strftime("cloud-init-logs-%Y-%m-%d") expected_logs = [ f"{dirname}/", f"{dirname}/dmesg.txt", @@ -98,7 +98,7 @@ def collect_logs(self, custom_client: IntegrationInstance): found_logs = custom_client.execute( "tar -tf cloud-init.tar.gz" ).stdout.splitlines() - dirname = datetime.utcnow().date().strftime("cloud-init-logs-%Y-%m-%d") + dirname = datetime.now(timezone.utc).date().strftime("cloud-init-logs-%Y-%m-%d") assert f"{dirname}/new-cloud-dir/data/result.json" in found_logs # LXD inserts some agent setup code into VMs on Bionic under diff --git a/tests/unittests/sources/azure/test_errors.py b/tests/unittests/sources/azure/test_errors.py index 7621f1f4ca0..43c0da61e14 100644 --- a/tests/unittests/sources/azure/test_errors.py +++ b/tests/unittests/sources/azure/test_errors.py @@ -20,9 +20,9 @@ def agent_string(): @pytest.fixture() def fake_utcnow(): - timestamp = datetime.datetime.utcnow() + timestamp = datetime.datetime.now(datetime.timezone.utc) with mock.patch.object(errors, "datetime", autospec=True) as m: - m.utcnow.return_value = timestamp + m.now.return_value = timestamp yield timestamp diff --git a/tests/unittests/sources/azure/test_kvp.py b/tests/unittests/sources/azure/test_kvp.py index b64ea6c8b9f..0404dcfcb00 100644 --- a/tests/unittests/sources/azure/test_kvp.py +++ b/tests/unittests/sources/azure/test_kvp.py @@ -1,6 +1,6 @@ # This file is part of cloud-init. See LICENSE file for license information. -from datetime import datetime +from datetime import datetime, timezone from unittest import mock import pytest @@ -11,9 +11,9 @@ @pytest.fixture() def fake_utcnow(): - timestamp = datetime.utcnow() + timestamp = datetime.now(timezone.utc) with mock.patch.object(kvp, "datetime", autospec=True) as m: - m.utcnow.return_value = timestamp + m.now.return_value = timestamp yield timestamp diff --git a/tests/unittests/sources/test_azure.py b/tests/unittests/sources/test_azure.py index a2ee3e29c89..fa82e41dafa 100644 --- a/tests/unittests/sources/test_azure.py +++ b/tests/unittests/sources/test_azure.py @@ -315,7 +315,7 @@ def mock_subp_subp(): @pytest.fixture def mock_timestamp(): - timestamp = datetime.datetime.utcnow() + timestamp = datetime.datetime.now(datetime.timezone.utc) with mock.patch.object(errors, "datetime", autospec=True) as m: m.utcnow.return_value = timestamp yield timestamp diff --git a/tests/unittests/sources/test_gce.py b/tests/unittests/sources/test_gce.py index 38935e05de5..dec79b53717 100644 --- a/tests/unittests/sources/test_gce.py +++ b/tests/unittests/sources/test_gce.py @@ -341,8 +341,8 @@ def test_get_data_returns_false_if_not_on_gce(self, m_fetcher): def test_has_expired(self): def _get_timestamp(days): - format_str = "%Y-%m-%dT%H:%M:%S+0000" - today = datetime.datetime.now() + format_str = "%Y-%m-%dT%H:%M:%S%z" + today = datetime.datetime.now(datetime.timezone.utc) timestamp = today + datetime.timedelta(days=days) return timestamp.strftime(format_str) diff --git a/tests/unittests/test_log.py b/tests/unittests/test_log.py index c3e83143165..a5cc2a6ee21 100644 --- a/tests/unittests/test_log.py +++ b/tests/unittests/test_log.py @@ -45,9 +45,20 @@ def test_logger_uses_gmtime(self): # parsed dt : 2017-08-23 14:19:43.069000 # utc_after : 2017-08-23 14:19:43.570064 - utc_before = datetime.datetime.utcnow() - datetime.timedelta(0, 0.5) + def remove_tz(_dt: datetime.datetime) -> datetime.datetime: + """ + Removes the timezone object from an aware datetime dt without + conversion of date and time data + """ + return _dt.replace(tzinfo=None) + + utc_before = remove_tz( + datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(0, 0.5) + ) self.LOG.error("Test message") - utc_after = datetime.datetime.utcnow() + datetime.timedelta(0, 0.5) + utc_after = remove_tz( + datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(0, 0.5) + ) # extract timestamp from log: # 2017-08-23 14:19:43,069 - test_log.py[ERROR]: Test message