Skip to content

Commit bec35f3

Browse files
authored
Move datetime.datetime.utcnow usage to consolidated function (aws#9636)
1 parent 3f115d1 commit bec35f3

File tree

15 files changed

+58
-42
lines changed

15 files changed

+58
-42
lines changed

awscli/compat.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
import collections.abc as collections_abc
1515
import contextlib
16+
import datetime
1617
import io
1718
import locale
1819
import os
@@ -502,3 +503,13 @@ def _linux_distribution(
502503
if _id:
503504
id = _id
504505
return distname, version, id
506+
507+
508+
def get_current_datetime(remove_tzinfo=True):
509+
# TODO: Consolidate to botocore.compat.get_current_datetime
510+
# after it's had time to bake to avoid import errors with
511+
# mismatched versions.
512+
datetime_now = datetime.datetime.now(datetime.timezone.utc)
513+
if remove_tzinfo:
514+
datetime_now = datetime_now.replace(tzinfo=None)
515+
return datetime_now

awscli/customizations/cloudformation/deployer.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,10 @@
1717
import botocore
1818
import collections
1919

20+
from awscli.compat import get_current_datetime
2021
from awscli.customizations.cloudformation import exceptions
2122
from awscli.customizations.cloudformation.artifact_exporter import mktempfile, parse_s3_url
2223

23-
from datetime import datetime
2424

2525
LOG = logging.getLogger(__name__)
2626

@@ -85,7 +85,7 @@ def create_changeset(self, stack_name, cfn_template,
8585
:return:
8686
"""
8787

88-
now = datetime.utcnow().isoformat()
88+
now = get_current_datetime().isoformat()
8989
description = "Created by AWS CLI at {0} UTC".format(now)
9090

9191
# Each changeset will get a unique name based on time

awscli/customizations/cloudtrail/validation.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
import sys
2020
import zlib
2121
from zlib import error as ZLibError
22-
from datetime import datetime, timedelta
22+
from datetime import timedelta
2323
from dateutil import tz, parser
2424

2525
from pyasn1.error import PyAsn1Error
@@ -29,6 +29,7 @@
2929
get_account_id_from_arn
3030
from awscli.customizations.commands import BasicCommand
3131
from botocore.exceptions import ClientError
32+
from awscli.compat import get_current_datetime
3233
from awscli.schema import ParameterRequiredError
3334
from awscli.utils import create_nested_client
3435

@@ -432,7 +433,7 @@ def traverse(self, start_date, end_date=None):
432433
:param end_date: Date to stop validating at (inclusive).
433434
"""
434435
if end_date is None:
435-
end_date = datetime.utcnow()
436+
end_date = get_current_datetime()
436437
end_date = normalize_date(end_date)
437438
start_date = normalize_date(start_date)
438439
bucket = self.starting_bucket
@@ -735,7 +736,7 @@ def handle_args(self, args):
735736
if args.end_time:
736737
self.end_time = normalize_date(parse_date(args.end_time))
737738
else:
738-
self.end_time = normalize_date(datetime.utcnow())
739+
self.end_time = normalize_date(get_current_datetime())
739740
if self.start_time > self.end_time:
740741
raise ValueError(('Invalid time range specified: start-time must '
741742
'occur before end-time'))

awscli/customizations/codecommit.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,12 @@
1616
import sys
1717
import logging
1818
import fileinput
19-
import datetime
2019

2120
from botocore.auth import SigV4Auth
2221
from botocore.awsrequest import AWSRequest
2322
from botocore.compat import urlsplit
2423
from awscli.customizations.commands import BasicCommand
25-
from awscli.compat import NonTranslatedStdout
24+
from awscli.compat import NonTranslatedStdout, get_current_datetime
2625

2726
logger = logging.getLogger('botocore.credentials')
2827

@@ -150,7 +149,7 @@ def sign_request(self, region, url_to_sign):
150149
request = AWSRequest()
151150
request.url = url_to_sign
152151
request.method = 'GIT'
153-
now = datetime.datetime.utcnow()
152+
now = get_current_datetime()
154153
request.context['timestamp'] = now.strftime('%Y%m%dT%H%M%S')
155154
split = urlsplit(request.url)
156155
# we don't want to include the port number in the signature

awscli/customizations/codedeploy/push.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,12 @@
1616
import zipfile
1717
import tempfile
1818
import contextlib
19-
from datetime import datetime
2019

2120
from botocore.exceptions import ClientError
2221

2322
from awscli.customizations.codedeploy.utils import validate_s3_location
2423
from awscli.customizations.commands import BasicCommand
25-
from awscli.compat import BytesIO, ZIP_COMPRESSION_MODE
24+
from awscli.compat import BytesIO, ZIP_COMPRESSION_MODE, get_current_datetime
2625
from awscli.utils import create_nested_client
2726

2827
ONE_MB = 1 << 20
@@ -132,7 +131,7 @@ def _validate_args(self, parsed_args):
132131
if not parsed_args.description:
133132
parsed_args.description = (
134133
'Uploaded by AWS CLI {0} UTC'.format(
135-
datetime.utcnow().isoformat()
134+
get_current_datetime().isoformat()
136135
)
137136
)
138137

awscli/customizations/datapipeline/__init__.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,11 @@
1212
# language governing permissions and limitations under the License.
1313

1414
import json
15-
from datetime import datetime, timedelta
15+
from datetime import timedelta
1616

1717
from awscli.formatter import get_formatter
1818
from awscli.arguments import CustomArgument
19+
from awscli.compat import get_current_datetime
1920
from awscli.customizations.commands import BasicCommand
2021
from awscli.customizations.datapipeline import translator
2122
from awscli.customizations.datapipeline.createdefaultroles \
@@ -184,7 +185,7 @@ class QueryArgBuilder(object):
184185
"""
185186
def __init__(self, current_time=None):
186187
if current_time is None:
187-
current_time = datetime.utcnow()
188+
current_time = get_current_datetime()
188189
self.current_time = current_time
189190

190191
def build_query(self, parsed_args):

awscli/customizations/ec2/bundleinstance.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import datetime
1919

2020
from awscli.arguments import CustomArgument
21+
from awscli.compat import get_current_datetime
2122

2223
logger = logging.getLogger('ec2bundleinstance')
2324

@@ -117,7 +118,7 @@ def _generate_policy(params):
117118
# Called if there is no policy supplied by the user.
118119
# Creates a policy that provides access for 24 hours.
119120
delta = datetime.timedelta(hours=24)
120-
expires = datetime.datetime.utcnow() + delta
121+
expires = get_current_datetime() + delta
121122
expires_iso = expires.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
122123
policy = POLICY.format(expires=expires_iso,
123124
bucket=params['Bucket'],

awscli/customizations/eks/get_token.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,13 @@
1616
import os
1717
import sys
1818

19-
from datetime import datetime, timedelta
19+
from datetime import timedelta
2020
from botocore.signers import RequestSigner
2121
from botocore.model import ServiceId
2222

2323
from awscli.formatter import get_formatter
2424
from awscli.utils import create_nested_client
25+
from awscli.compat import get_current_datetime
2526
from awscli.customizations.commands import BasicCommand
2627
from awscli.customizations.utils import uni_print
2728
from awscli.customizations.utils import validate_mutually_exclusive
@@ -107,7 +108,7 @@ class GetTokenCommand(BasicCommand):
107108
]
108109

109110
def get_expiration_time(self):
110-
token_expiration = datetime.utcnow() + timedelta(
111+
token_expiration = get_current_datetime() + timedelta(
111112
minutes=TOKEN_EXPIRATION_MINS
112113
)
113114
return token_expiration.strftime('%Y-%m-%dT%H:%M:%SZ')

awscli/customizations/opsworks.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424

2525
from botocore.exceptions import ClientError
2626

27-
from awscli.compat import urlopen, ensure_text_type
27+
from awscli.compat import get_current_datetime, urlopen, ensure_text_type
2828
from awscli.customizations.commands import BasicCommand
2929
from awscli.customizations.utils import create_client_from_parsed_globals
3030

@@ -505,7 +505,7 @@ def _iam_policy_document(arn, timeout=None):
505505
"Resource": arn,
506506
}
507507
if timeout is not None:
508-
valid_until = datetime.datetime.utcnow() + timeout
508+
valid_until = get_current_datetime() + timeout
509509
statement["Condition"] = {
510510
"DateLessThan": {
511511
"aws:CurrentTime":

tests/functional/ec2/test_bundle_instance.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ class TestBundleInstance(BaseAWSCommandParamsTest):
3131

3232
def setUp(self):
3333
super(TestBundleInstance, self).setUp()
34-
# This mocks out datetime.datetime.utcnow() so that it always
34+
# This mocks out datetime.datetime.now() so that it always
3535
# returns the same datetime object. This is because this value
3636
# is embedded into the policy file that is generated and we
3737
# don't what the policy or its signature to change each time
@@ -41,7 +41,7 @@ def setUp(self):
4141
mock.Mock(wraps=datetime.datetime)
4242
)
4343
mocked_datetime = self.datetime_patcher.start()
44-
mocked_datetime.utcnow.return_value = datetime.datetime(2013, 8, 9)
44+
mocked_datetime.now.return_value = datetime.datetime(2013, 8, 9)
4545

4646
def tearDown(self):
4747
super(TestBundleInstance, self).tearDown()

0 commit comments

Comments
 (0)