From bb61f0186d5c490caa44f3e3672d81e14414d33c Mon Sep 17 00:00:00 2001 From: Carlton Gibson Date: Wed, 23 Mar 2022 12:15:36 +0100 Subject: [PATCH] Refs #32365 -- Removed internal uses of utils.timezone.utc alias. Remaining test case ensures that uses of the alias are mapped canonically by the migration writer. --- .../contrib/humanize/templatetags/humanize.py | 6 +-- django/contrib/sessions/backends/file.py | 3 +- django/contrib/sitemaps/views.py | 2 +- django/core/cache/backends/db.py | 10 ++-- django/core/files/storage.py | 3 +- django/db/backends/base/base.py | 4 +- django/db/models/fields/__init__.py | 2 +- django/http/response.py | 4 +- django/templatetags/tz.py | 6 ++- django/utils/dateparse.py | 4 +- django/utils/feedgenerator.py | 3 +- django/utils/timesince.py | 4 +- django/utils/timezone.py | 2 +- django/views/decorators/http.py | 4 +- docs/ref/models/database-functions.txt | 16 +++--- docs/topics/i18n/timezones.txt | 2 +- tests/aggregation/tests.py | 6 +-- tests/auth_tests/test_remote_user.py | 3 +- tests/datatypes/tests.py | 3 +- .../datetime/test_extract_trunc.py | 9 ++-- tests/file_storage/tests.py | 5 +- .../field_tests/test_datetimefield.py | 8 +-- tests/generic_views/test_dates.py | 49 ++++++++++++++----- tests/humanize_tests/tests.py | 6 +-- tests/migrations/test_writer.py | 2 +- tests/postgres_tests/test_ranges.py | 7 +-- tests/responses/test_cookie.py | 9 ++-- tests/schema/tests.py | 3 +- tests/staticfiles_tests/storage.py | 3 +- tests/staticfiles_tests/test_management.py | 3 +- tests/timezones/tests.py | 6 +-- tests/utils_tests/test_dateformat.py | 13 ++--- tests/utils_tests/test_feedgenerator.py | 7 ++- 33 files changed, 115 insertions(+), 102 deletions(-) diff --git a/django/contrib/humanize/templatetags/humanize.py b/django/contrib/humanize/templatetags/humanize.py index 02c731331b..23224779c5 100644 --- a/django/contrib/humanize/templatetags/humanize.py +++ b/django/contrib/humanize/templatetags/humanize.py @@ -1,12 +1,12 @@ import re -from datetime import date, datetime +from datetime import date, datetime, timezone from decimal import Decimal from django import template from django.template import defaultfilters from django.utils.formats import number_format from django.utils.safestring import mark_safe -from django.utils.timezone import is_aware, utc +from django.utils.timezone import is_aware from django.utils.translation import gettext as _ from django.utils.translation import ( gettext_lazy, @@ -283,7 +283,7 @@ class NaturalTimeFormatter: if not isinstance(value, date): # datetime is a subclass of date return value - now = datetime.now(utc if is_aware(value) else None) + now = datetime.now(timezone.utc if is_aware(value) else None) if value < now: delta = now - value if delta.days != 0: diff --git a/django/contrib/sessions/backends/file.py b/django/contrib/sessions/backends/file.py index 947388333f..b7a13d6d17 100644 --- a/django/contrib/sessions/backends/file.py +++ b/django/contrib/sessions/backends/file.py @@ -13,7 +13,6 @@ from django.contrib.sessions.backends.base import ( ) from django.contrib.sessions.exceptions import InvalidSessionKey from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation -from django.utils import timezone class SessionStore(SessionBase): @@ -65,7 +64,7 @@ class SessionStore(SessionBase): Return the modification time of the file storing the session's content. """ modification = os.stat(self._key_to_file()).st_mtime - tz = timezone.utc if settings.USE_TZ else None + tz = datetime.timezone.utc if settings.USE_TZ else None return datetime.datetime.fromtimestamp(modification, tz=tz) def _expiry_date(self, session_data): diff --git a/django/contrib/sitemaps/views.py b/django/contrib/sitemaps/views.py index 41c115de49..679f7ed611 100644 --- a/django/contrib/sitemaps/views.py +++ b/django/contrib/sitemaps/views.py @@ -46,7 +46,7 @@ def _get_latest_lastmod(current_lastmod, new_lastmod): if not isinstance(new_lastmod, datetime.datetime): new_lastmod = datetime.datetime.combine(new_lastmod, datetime.time.min) if timezone.is_naive(new_lastmod): - new_lastmod = timezone.make_aware(new_lastmod, timezone.utc) + new_lastmod = timezone.make_aware(new_lastmod, datetime.timezone.utc) return new_lastmod if current_lastmod is None else max(current_lastmod, new_lastmod) diff --git a/django/core/cache/backends/db.py b/django/core/cache/backends/db.py index e3d055084c..e022b96abe 100644 --- a/django/core/cache/backends/db.py +++ b/django/core/cache/backends/db.py @@ -1,12 +1,12 @@ "Database cache backend." import base64 import pickle -from datetime import datetime +from datetime import datetime, timezone from django.conf import settings from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache from django.db import DatabaseError, connections, models, router, transaction -from django.utils import timezone +from django.utils.timezone import now as tz_now class Options: @@ -89,7 +89,7 @@ class DatabaseCache(BaseDatabaseCache): for key, value, expires in rows: for converter in converters: expires = converter(expires, expression, connection) - if expires < timezone.now(): + if expires < tz_now(): expired_keys.append(key) else: value = connection.ops.process_clob(value) @@ -120,7 +120,7 @@ class DatabaseCache(BaseDatabaseCache): with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM %s" % table) num = cursor.fetchone()[0] - now = timezone.now() + now = tz_now() now = now.replace(microsecond=0) if timeout is None: exp = datetime.max @@ -239,7 +239,7 @@ class DatabaseCache(BaseDatabaseCache): connection = connections[db] quote_name = connection.ops.quote_name - now = timezone.now().replace(microsecond=0, tzinfo=None) + now = tz_now().replace(microsecond=0, tzinfo=None) with connection.cursor() as cursor: cursor.execute( diff --git a/django/core/files/storage.py b/django/core/files/storage.py index 714f9c1255..71cbb93cb6 100644 --- a/django/core/files/storage.py +++ b/django/core/files/storage.py @@ -1,6 +1,6 @@ import os import pathlib -from datetime import datetime +from datetime import datetime, timezone from urllib.parse import urljoin from django.conf import settings @@ -9,7 +9,6 @@ from django.core.files import File, locks from django.core.files.move import file_move_safe from django.core.files.utils import validate_file_name from django.core.signals import setting_changed -from django.utils import timezone from django.utils._os import safe_join from django.utils.crypto import get_random_string from django.utils.deconstruct import deconstructible diff --git a/django/db/backends/base/base.py b/django/db/backends/base/base.py index f093f2bd8b..f8bea6fd23 100644 --- a/django/db/backends/base/base.py +++ b/django/db/backends/base/base.py @@ -1,5 +1,6 @@ import _thread import copy +import datetime import threading import time import warnings @@ -19,7 +20,6 @@ from django.db.backends.base.validation import BaseDatabaseValidation from django.db.backends.signals import connection_created from django.db.transaction import TransactionManagementError from django.db.utils import DatabaseErrorWrapper -from django.utils import timezone from django.utils.asyncio import async_unsafe from django.utils.functional import cached_property @@ -157,7 +157,7 @@ class BaseDatabaseWrapper: if not settings.USE_TZ: return None elif self.settings_dict["TIME_ZONE"] is None: - return timezone.utc + return datetime.timezone.utc else: return timezone_constructor(self.settings_dict["TIME_ZONE"]) diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index 4d17c25f0f..72208efd04 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -1212,7 +1212,7 @@ class CommaSeparatedIntegerField(CharField): def _to_naive(value): if timezone.is_aware(value): - value = timezone.make_naive(value, timezone.utc) + value = timezone.make_naive(value, datetime.timezone.utc) return value diff --git a/django/http/response.py b/django/http/response.py index 801a0c0640..62b8b1c087 100644 --- a/django/http/response.py +++ b/django/http/response.py @@ -236,8 +236,8 @@ class HttpResponseBase: if expires is not None: if isinstance(expires, datetime.datetime): if timezone.is_naive(expires): - expires = timezone.make_aware(expires, timezone.utc) - delta = expires - datetime.datetime.now(tz=timezone.utc) + expires = timezone.make_aware(expires, datetime.timezone.utc) + delta = expires - datetime.datetime.now(tz=datetime.timezone.utc) # Add one second so the date matches exactly (a fraction of # time gets lost between converting to a timedelta and # then the date string). diff --git a/django/templatetags/tz.py b/django/templatetags/tz.py index de0432cd4d..cb7d22e5f2 100644 --- a/django/templatetags/tz.py +++ b/django/templatetags/tz.py @@ -1,4 +1,6 @@ -from datetime import datetime, tzinfo +from datetime import datetime +from datetime import timezone as datetime_timezone +from datetime import tzinfo try: import zoneinfo @@ -57,7 +59,7 @@ def utc(value): """ Convert a datetime to UTC. """ - return do_timezone(value, timezone.utc) + return do_timezone(value, datetime_timezone.utc) @register.filter("timezone") diff --git a/django/utils/dateparse.py b/django/utils/dateparse.py index 2e6a260a4f..08651f57ad 100644 --- a/django/utils/dateparse.py +++ b/django/utils/dateparse.py @@ -8,7 +8,7 @@ import datetime from django.utils.regex_helper import _lazy_re_compile -from django.utils.timezone import get_fixed_timezone, utc +from django.utils.timezone import get_fixed_timezone date_re = _lazy_re_compile(r"(?P\d{4})-(?P\d{1,2})-(?P\d{1,2})$") @@ -118,7 +118,7 @@ def parse_datetime(value): kw["microsecond"] = kw["microsecond"] and kw["microsecond"].ljust(6, "0") tzinfo = kw.pop("tzinfo") if tzinfo == "Z": - tzinfo = utc + tzinfo = datetime.timezone.utc elif tzinfo is not None: offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0 offset = 60 * int(tzinfo[1:3]) + offset_mins diff --git a/django/utils/feedgenerator.py b/django/utils/feedgenerator.py index 5a57db19ec..31ca9a2db9 100644 --- a/django/utils/feedgenerator.py +++ b/django/utils/feedgenerator.py @@ -27,7 +27,6 @@ from io import StringIO from urllib.parse import urlparse from django.utils.encoding import iri_to_uri -from django.utils.timezone import utc from django.utils.xmlutils import SimplerXMLGenerator @@ -210,7 +209,7 @@ class SyndicationFeed: if latest_date is None or item_date > latest_date: latest_date = item_date - return latest_date or datetime.datetime.now(tz=utc) + return latest_date or datetime.datetime.now(tz=datetime.timezone.utc) class Enclosure: diff --git a/django/utils/timesince.py b/django/utils/timesince.py index 8a8ffb8151..3a0d4afb1a 100644 --- a/django/utils/timesince.py +++ b/django/utils/timesince.py @@ -2,7 +2,7 @@ import calendar import datetime from django.utils.html import avoid_wrapping -from django.utils.timezone import is_aware, utc +from django.utils.timezone import is_aware from django.utils.translation import gettext, ngettext_lazy TIME_STRINGS = { @@ -54,7 +54,7 @@ def timesince(d, now=None, reversed=False, time_strings=None, depth=2): if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) - now = now or datetime.datetime.now(utc if is_aware(d) else None) + now = now or datetime.datetime.now(datetime.timezone.utc if is_aware(d) else None) if reversed: d, now = now, d diff --git a/django/utils/timezone.py b/django/utils/timezone.py index 71b160448e..33c0440095 100644 --- a/django/utils/timezone.py +++ b/django/utils/timezone.py @@ -224,7 +224,7 @@ def now(): """ Return an aware or naive datetime.datetime, depending on settings.USE_TZ. """ - return datetime.now(tz=utc if settings.USE_TZ else None) + return datetime.now(tz=timezone.utc if settings.USE_TZ else None) # By design, these four functions don't perform any checks on their arguments. diff --git a/django/views/decorators/http.py b/django/views/decorators/http.py index 6f7578ef31..6d88a633eb 100644 --- a/django/views/decorators/http.py +++ b/django/views/decorators/http.py @@ -1,7 +1,7 @@ """ Decorators for views based on HTTP headers. """ - +import datetime from functools import wraps from django.http import HttpResponseNotAllowed @@ -91,7 +91,7 @@ def condition(etag_func=None, last_modified_func=None): dt = last_modified_func(request, *args, **kwargs) if dt: if not timezone.is_aware(dt): - dt = timezone.make_aware(dt, timezone.utc) + dt = timezone.make_aware(dt, datetime.timezone.utc) return int(dt.timestamp()) # The value from etag_func() could be quoted or unquoted. diff --git a/docs/ref/models/database-functions.txt b/docs/ref/models/database-functions.txt index 28d489d256..acca4a7c68 100644 --- a/docs/ref/models/database-functions.txt +++ b/docs/ref/models/database-functions.txt @@ -358,8 +358,7 @@ as ``__(lookup_name)``, e.g. ``__year``. Since ``DateField``\s don't have a time component, only ``Extract`` subclasses that deal with date-parts can be used with ``DateField``:: - >>> from datetime import datetime - >>> from django.utils import timezone + >>> from datetime import datetime, timezone >>> from django.db.models.functions import ( ... ExtractDay, ExtractMonth, ExtractQuarter, ExtractWeek, ... ExtractIsoWeekDay, ExtractWeekDay, ExtractIsoYear, ExtractYear, @@ -409,8 +408,7 @@ Each class is also a ``Transform`` registered on ``DateTimeField`` as ``DateTimeField`` examples:: - >>> from datetime import datetime - >>> from django.utils import timezone + >>> from datetime import datetime, timezone >>> from django.db.models.functions import ( ... ExtractDay, ExtractHour, ExtractMinute, ExtractMonth, ... ExtractQuarter, ExtractSecond, ExtractWeek, ExtractIsoWeekDay, @@ -447,6 +445,7 @@ to that timezone before the value is extracted. The example below converts to the Melbourne timezone (UTC +10:00), which changes the day, weekday, and hour values that are returned:: + >>> from django.utils import timezone >>> import zoneinfo >>> melb = zoneinfo.ZoneInfo('Australia/Melbourne') # UTC+10:00 >>> with timezone.override(melb): @@ -620,10 +619,9 @@ with less precision. ``expression`` can have an ``output_field`` of either Since ``DateField``\s don't have a time component, only ``Trunc`` subclasses that deal with date-parts can be used with ``DateField``:: - >>> from datetime import datetime + >>> from datetime import datetime, timezone >>> from django.db.models import Count >>> from django.db.models.functions import TruncMonth, TruncYear - >>> from django.utils import timezone >>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc) >>> start2 = datetime(2015, 6, 15, 14, 40, 2, 123, tzinfo=timezone.utc) >>> start3 = datetime(2015, 12, 31, 17, 5, 27, 999, tzinfo=timezone.utc) @@ -699,12 +697,11 @@ datetimes with less precision. ``expression`` must have an ``output_field`` of Usage example:: - >>> from datetime import date, datetime + >>> from datetime import date, datetime, timezone >>> from django.db.models import Count >>> from django.db.models.functions import ( ... TruncDate, TruncDay, TruncHour, TruncMinute, TruncSecond, ... ) - >>> from django.utils import timezone >>> import zoneinfo >>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc) >>> Experiment.objects.create(start_datetime=start1, start_date=start1.date()) @@ -753,10 +750,9 @@ with less precision. ``expression`` can have an ``output_field`` of either Since ``TimeField``\s don't have a date component, only ``Trunc`` subclasses that deal with time-parts can be used with ``TimeField``:: - >>> from datetime import datetime + >>> from datetime import datetime, timezone >>> from django.db.models import Count, TimeField >>> from django.db.models.functions import TruncHour - >>> from django.utils import timezone >>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc) >>> start2 = datetime(2014, 6, 15, 14, 40, 2, 123, tzinfo=timezone.utc) >>> start3 = datetime(2015, 12, 31, 17, 5, 27, 999, tzinfo=timezone.utc) diff --git a/docs/topics/i18n/timezones.txt b/docs/topics/i18n/timezones.txt index 4c6aa58ba2..318a16d6ab 100644 --- a/docs/topics/i18n/timezones.txt +++ b/docs/topics/i18n/timezones.txt @@ -151,7 +151,7 @@ used. However, :ref:`as explained above `, this isn't entirely reliable, and you should always work with aware datetimes in UTC in your own code. For instance, use :meth:`~datetime.datetime.fromtimestamp` - and set the ``tz`` parameter to :data:`~django.utils.timezone.utc`. + and set the ``tz`` parameter to :attr:`~datetime.timezone.utc`. Selecting the current time zone ------------------------------- diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py index 4ca8729a4b..b779fe551c 100644 --- a/tests/aggregation/tests.py +++ b/tests/aggregation/tests.py @@ -1847,7 +1847,7 @@ class AggregateTestCase(TestCase): ) def test_aggregation_default_using_time_from_database(self): - now = timezone.now().astimezone(timezone.utc) + now = timezone.now().astimezone(datetime.timezone.utc) expr = Min( "store__friday_night_closing", filter=~Q(store__name="Amazon.com"), @@ -1899,7 +1899,7 @@ class AggregateTestCase(TestCase): ) def test_aggregation_default_using_date_from_database(self): - now = timezone.now().astimezone(timezone.utc) + now = timezone.now().astimezone(datetime.timezone.utc) expr = Min("book__pubdate", default=TruncDate(NowUTC())) queryset = Publisher.objects.annotate(earliest_pubdate=expr).order_by("name") self.assertSequenceEqual( @@ -1960,7 +1960,7 @@ class AggregateTestCase(TestCase): ) def test_aggregation_default_using_datetime_from_database(self): - now = timezone.now().astimezone(timezone.utc) + now = timezone.now().astimezone(datetime.timezone.utc) expr = Min( "store__original_opening", filter=~Q(store__name="Amazon.com"), diff --git a/tests/auth_tests/test_remote_user.py b/tests/auth_tests/test_remote_user.py index 8fb1b972b5..9e6e0dce20 100644 --- a/tests/auth_tests/test_remote_user.py +++ b/tests/auth_tests/test_remote_user.py @@ -1,4 +1,4 @@ -from datetime import datetime +from datetime import datetime, timezone from django.conf import settings from django.contrib.auth import authenticate @@ -13,7 +13,6 @@ from django.test import ( modify_settings, override_settings, ) -from django.utils import timezone from django.utils.deprecation import RemovedInDjango50Warning diff --git a/tests/datatypes/tests.py b/tests/datatypes/tests.py index 56f6c14c31..97f3ec0852 100644 --- a/tests/datatypes/tests.py +++ b/tests/datatypes/tests.py @@ -1,7 +1,6 @@ import datetime from django.test import TestCase, skipIfDBFeature -from django.utils.timezone import utc from .models import Donut, RumBaba @@ -94,7 +93,7 @@ class DataTypesTestCase(TestCase): def test_error_on_timezone(self): """Regression test for #8354: the MySQL and Oracle backends should raise an error if given a timezone-aware datetime object.""" - dt = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=utc) + dt = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=datetime.timezone.utc) d = Donut(name="Bear claw", consumed_at=dt) # MySQL backend does not support timezone-aware datetimes. with self.assertRaises(ValueError): diff --git a/tests/db_functions/datetime/test_extract_trunc.py b/tests/db_functions/datetime/test_extract_trunc.py index a01778c719..0c08ccf106 100644 --- a/tests/db_functions/datetime/test_extract_trunc.py +++ b/tests/db_functions/datetime/test_extract_trunc.py @@ -1606,7 +1606,7 @@ class DateFunctionTests(TestCase): outer = Author.objects.annotate( newest_fan_year=TruncYear(Subquery(inner, output_field=DateTimeField())) ) - tz = timezone.utc if settings.USE_TZ else None + tz = datetime_timezone.utc if settings.USE_TZ else None self.assertSequenceEqual( outer.order_by("name").values("name", "newest_fan_year"), [ @@ -1758,7 +1758,7 @@ class DateFunctionWithTimeZoneTests(DateFunctionTests): DTModel.objects.annotate( day_melb=Extract("start_datetime", "day"), day_utc=Extract( - "start_datetime", "day", tzinfo=timezone.utc + "start_datetime", "day", tzinfo=datetime_timezone.utc ), ) .order_by("start_datetime") @@ -1826,9 +1826,8 @@ class DateFunctionWithTimeZoneTests(DateFunctionTests): @ignore_warnings(category=RemovedInDjango50Warning) def test_trunc_ambiguous_and_invalid_times(self): sao = pytz.timezone("America/Sao_Paulo") - utc = timezone.utc - start_datetime = datetime(2016, 10, 16, 13, tzinfo=utc) - end_datetime = datetime(2016, 2, 21, 1, tzinfo=utc) + start_datetime = datetime(2016, 10, 16, 13, tzinfo=datetime_timezone.utc) + end_datetime = datetime(2016, 2, 21, 1, tzinfo=datetime_timezone.utc) self.create_model(start_datetime, end_datetime) with timezone.override(sao): with self.assertRaisesMessage( diff --git a/tests/file_storage/tests.py b/tests/file_storage/tests.py index f7bbb343d6..87a5e70c33 100644 --- a/tests/file_storage/tests.py +++ b/tests/file_storage/tests.py @@ -6,6 +6,7 @@ import threading import time import unittest from datetime import datetime, timedelta +from datetime import timezone as datetime_timezone from io import StringIO from pathlib import Path from urllib.request import urlopen @@ -168,7 +169,7 @@ class FileStorageTests(SimpleTestCase): naive_now = datetime.now() algiers_offset = now_in_algiers.tzinfo.utcoffset(naive_now) django_offset = timezone.get_current_timezone().utcoffset(naive_now) - utc_offset = timezone.utc.utcoffset(naive_now) + utc_offset = datetime_timezone.utc.utcoffset(naive_now) self.assertGreater(algiers_offset, utc_offset) self.assertLess(django_offset, utc_offset) @@ -199,7 +200,7 @@ class FileStorageTests(SimpleTestCase): naive_now = datetime.now() algiers_offset = now_in_algiers.tzinfo.utcoffset(naive_now) django_offset = timezone.get_current_timezone().utcoffset(naive_now) - utc_offset = timezone.utc.utcoffset(naive_now) + utc_offset = datetime_timezone.utc.utcoffset(naive_now) self.assertGreater(algiers_offset, utc_offset) self.assertLess(django_offset, utc_offset) diff --git a/tests/forms_tests/field_tests/test_datetimefield.py b/tests/forms_tests/field_tests/test_datetimefield.py index 3d266da6b7..af303b0436 100644 --- a/tests/forms_tests/field_tests/test_datetimefield.py +++ b/tests/forms_tests/field_tests/test_datetimefield.py @@ -1,9 +1,9 @@ -from datetime import date, datetime +from datetime import date, datetime, timezone from django.core.exceptions import ValidationError from django.forms import DateTimeField from django.test import SimpleTestCase -from django.utils.timezone import get_fixed_timezone, utc +from django.utils.timezone import get_fixed_timezone class DateTimeFieldTest(SimpleTestCase): @@ -40,7 +40,7 @@ class DateTimeFieldTest(SimpleTestCase): ("2014-09-23T22:34:41", datetime(2014, 9, 23, 22, 34, 41)), ("2014-09-23T22:34", datetime(2014, 9, 23, 22, 34)), ("2014-09-23", datetime(2014, 9, 23, 0, 0)), - ("2014-09-23T22:34Z", datetime(2014, 9, 23, 22, 34, tzinfo=utc)), + ("2014-09-23T22:34Z", datetime(2014, 9, 23, 22, 34, tzinfo=timezone.utc)), ( "2014-09-23T22:34+07:00", datetime(2014, 9, 23, 22, 34, tzinfo=get_fixed_timezone(420)), @@ -57,7 +57,7 @@ class DateTimeFieldTest(SimpleTestCase): " 2014-09-23T22:34:41.614804 ", datetime(2014, 9, 23, 22, 34, 41, 614804), ), - (" 2014-09-23T22:34Z ", datetime(2014, 9, 23, 22, 34, tzinfo=utc)), + (" 2014-09-23T22:34Z ", datetime(2014, 9, 23, 22, 34, tzinfo=timezone.utc)), ] f = DateTimeField() for value, expected_datetime in tests: diff --git a/tests/generic_views/test_dates.py b/tests/generic_views/test_dates.py index 9edcf8f688..90476270cc 100644 --- a/tests/generic_views/test_dates.py +++ b/tests/generic_views/test_dates.py @@ -4,7 +4,6 @@ from unittest import mock from django.core.exceptions import ImproperlyConfigured from django.test import TestCase, override_settings, skipUnlessDBFeature from django.test.utils import requires_tz_support -from django.utils import timezone from .models import Artist, Author, Book, BookSigning, Page @@ -157,7 +156,9 @@ class ArchiveIndexViewTests(TestDataMixin, TestCase): @override_settings(USE_TZ=True, TIME_ZONE="Africa/Nairobi") def test_aware_datetime_archive_view(self): BookSigning.objects.create( - event_date=datetime.datetime(2008, 4, 2, 12, 0, tzinfo=timezone.utc) + event_date=datetime.datetime( + 2008, 4, 2, 12, 0, tzinfo=datetime.timezone.utc + ) ) res = self.client.get("/dates/booksignings/") self.assertEqual(res.status_code, 200) @@ -344,7 +345,9 @@ class YearArchiveViewTests(TestDataMixin, TestCase): @override_settings(USE_TZ=True, TIME_ZONE="Africa/Nairobi") def test_aware_datetime_year_view(self): BookSigning.objects.create( - event_date=datetime.datetime(2008, 4, 2, 12, 0, tzinfo=timezone.utc) + event_date=datetime.datetime( + 2008, 4, 2, 12, 0, tzinfo=datetime.timezone.utc + ) ) res = self.client.get("/dates/booksignings/2008/") self.assertEqual(res.status_code, 200) @@ -517,13 +520,19 @@ class MonthArchiveViewTests(TestDataMixin, TestCase): @override_settings(USE_TZ=True, TIME_ZONE="Africa/Nairobi") def test_aware_datetime_month_view(self): BookSigning.objects.create( - event_date=datetime.datetime(2008, 2, 1, 12, 0, tzinfo=timezone.utc) + event_date=datetime.datetime( + 2008, 2, 1, 12, 0, tzinfo=datetime.timezone.utc + ) ) BookSigning.objects.create( - event_date=datetime.datetime(2008, 4, 2, 12, 0, tzinfo=timezone.utc) + event_date=datetime.datetime( + 2008, 4, 2, 12, 0, tzinfo=datetime.timezone.utc + ) ) BookSigning.objects.create( - event_date=datetime.datetime(2008, 6, 3, 12, 0, tzinfo=timezone.utc) + event_date=datetime.datetime( + 2008, 6, 3, 12, 0, tzinfo=datetime.timezone.utc + ) ) res = self.client.get("/dates/booksignings/2008/apr/") self.assertEqual(res.status_code, 200) @@ -664,7 +673,9 @@ class WeekArchiveViewTests(TestDataMixin, TestCase): @override_settings(USE_TZ=True, TIME_ZONE="Africa/Nairobi") def test_aware_datetime_week_view(self): BookSigning.objects.create( - event_date=datetime.datetime(2008, 4, 2, 12, 0, tzinfo=timezone.utc) + event_date=datetime.datetime( + 2008, 4, 2, 12, 0, tzinfo=datetime.timezone.utc + ) ) res = self.client.get("/dates/booksignings/2008/week/13/") self.assertEqual(res.status_code, 200) @@ -794,19 +805,25 @@ class DayArchiveViewTests(TestDataMixin, TestCase): @override_settings(USE_TZ=True, TIME_ZONE="Africa/Nairobi") def test_aware_datetime_day_view(self): bs = BookSigning.objects.create( - event_date=datetime.datetime(2008, 4, 2, 12, 0, tzinfo=timezone.utc) + event_date=datetime.datetime( + 2008, 4, 2, 12, 0, tzinfo=datetime.timezone.utc + ) ) res = self.client.get("/dates/booksignings/2008/apr/2/") self.assertEqual(res.status_code, 200) # 2008-04-02T00:00:00+03:00 (beginning of day) > # 2008-04-01T22:00:00+00:00 (book signing event date). - bs.event_date = datetime.datetime(2008, 4, 1, 22, 0, tzinfo=timezone.utc) + bs.event_date = datetime.datetime( + 2008, 4, 1, 22, 0, tzinfo=datetime.timezone.utc + ) bs.save() res = self.client.get("/dates/booksignings/2008/apr/2/") self.assertEqual(res.status_code, 200) # 2008-04-03T00:00:00+03:00 (end of day) > 2008-04-02T22:00:00+00:00 # (book signing event date). - bs.event_date = datetime.datetime(2008, 4, 2, 22, 0, tzinfo=timezone.utc) + bs.event_date = datetime.datetime( + 2008, 4, 2, 22, 0, tzinfo=datetime.timezone.utc + ) bs.save() res = self.client.get("/dates/booksignings/2008/apr/2/") self.assertEqual(res.status_code, 404) @@ -897,19 +914,25 @@ class DateDetailViewTests(TestDataMixin, TestCase): @override_settings(USE_TZ=True, TIME_ZONE="Africa/Nairobi") def test_aware_datetime_date_detail(self): bs = BookSigning.objects.create( - event_date=datetime.datetime(2008, 4, 2, 12, 0, tzinfo=timezone.utc) + event_date=datetime.datetime( + 2008, 4, 2, 12, 0, tzinfo=datetime.timezone.utc + ) ) res = self.client.get("/dates/booksignings/2008/apr/2/%d/" % bs.pk) self.assertEqual(res.status_code, 200) # 2008-04-02T00:00:00+03:00 (beginning of day) > # 2008-04-01T22:00:00+00:00 (book signing event date). - bs.event_date = datetime.datetime(2008, 4, 1, 22, 0, tzinfo=timezone.utc) + bs.event_date = datetime.datetime( + 2008, 4, 1, 22, 0, tzinfo=datetime.timezone.utc + ) bs.save() res = self.client.get("/dates/booksignings/2008/apr/2/%d/" % bs.pk) self.assertEqual(res.status_code, 200) # 2008-04-03T00:00:00+03:00 (end of day) > 2008-04-02T22:00:00+00:00 # (book signing event date). - bs.event_date = datetime.datetime(2008, 4, 2, 22, 0, tzinfo=timezone.utc) + bs.event_date = datetime.datetime( + 2008, 4, 2, 22, 0, tzinfo=datetime.timezone.utc + ) bs.save() res = self.client.get("/dates/booksignings/2008/apr/2/%d/" % bs.pk) self.assertEqual(res.status_code, 404) diff --git a/tests/humanize_tests/tests.py b/tests/humanize_tests/tests.py index c98bab382d..432314f795 100644 --- a/tests/humanize_tests/tests.py +++ b/tests/humanize_tests/tests.py @@ -6,7 +6,7 @@ from django.template import Context, Template, defaultfilters from django.test import SimpleTestCase, modify_settings, override_settings from django.utils import translation from django.utils.html import escape -from django.utils.timezone import get_fixed_timezone, utc +from django.utils.timezone import get_fixed_timezone from django.utils.translation import gettext as _ # Mock out datetime in some tests so they don't fail occasionally when they @@ -359,7 +359,7 @@ class HumanizeTests(SimpleTestCase): def test_naturalday_uses_localtime(self): # Regression for #18504 # This is 2012-03-08HT19:30:00-06:00 in America/Chicago - dt = datetime.datetime(2012, 3, 9, 1, 30, tzinfo=utc) + dt = datetime.datetime(2012, 3, 9, 1, 30, tzinfo=datetime.timezone.utc) orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime try: @@ -396,7 +396,7 @@ class HumanizeTests(SimpleTestCase): now + datetime.timedelta(days=2, hours=6), now + datetime.timedelta(days=500), now.replace(tzinfo=naive()), - now.replace(tzinfo=utc), + now.replace(tzinfo=datetime.timezone.utc), ] result_list = [ "test", diff --git a/tests/migrations/test_writer.py b/tests/migrations/test_writer.py index 07a2db989c..3e95ca6c15 100644 --- a/tests/migrations/test_writer.py +++ b/tests/migrations/test_writer.py @@ -909,7 +909,7 @@ class WriterTests(SimpleTestCase): Test comments at top of file. """ migration = type("Migration", (migrations.Migration,), {"operations": []}) - dt = datetime.datetime(2015, 7, 31, 4, 40, 0, 0, tzinfo=utc) + dt = datetime.datetime(2015, 7, 31, 4, 40, 0, 0, tzinfo=datetime.timezone.utc) with mock.patch("django.db.migrations.writer.now", lambda: dt): for include_header in (True, False): with self.subTest(include_header=include_header): diff --git a/tests/postgres_tests/test_ranges.py b/tests/postgres_tests/test_ranges.py index aaef47d6be..86722a9f46 100644 --- a/tests/postgres_tests/test_ranges.py +++ b/tests/postgres_tests/test_ranges.py @@ -563,8 +563,8 @@ class TestSerialization(PostgreSQLSimpleTestCase): lower_date = datetime.date(2014, 1, 1) upper_date = datetime.date(2014, 2, 2) - lower_dt = datetime.datetime(2014, 1, 1, 0, 0, 0, tzinfo=timezone.utc) - upper_dt = datetime.datetime(2014, 2, 2, 12, 12, 12, tzinfo=timezone.utc) + lower_dt = datetime.datetime(2014, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc) + upper_dt = datetime.datetime(2014, 2, 2, 12, 12, 12, tzinfo=datetime.timezone.utc) def test_dumping(self): instance = RangesModel( @@ -991,7 +991,8 @@ class TestFormField(PostgreSQLSimpleTestCase): field = pg_forms.DateTimeRangeField() value = field.prepare_value( DateTimeTZRange( - datetime.datetime(2015, 5, 22, 16, 6, 33, tzinfo=timezone.utc), None + datetime.datetime(2015, 5, 22, 16, 6, 33, tzinfo=datetime.timezone.utc), + None, ) ) self.assertEqual(value, [datetime.datetime(2015, 5, 22, 18, 6, 33), None]) diff --git a/tests/responses/test_cookie.py b/tests/responses/test_cookie.py index b6610cbaab..ea92584151 100644 --- a/tests/responses/test_cookie.py +++ b/tests/responses/test_cookie.py @@ -1,12 +1,11 @@ import time -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from http import cookies from django.http import HttpResponse from django.test import SimpleTestCase from django.test.utils import freeze_time from django.utils.http import http_date -from django.utils.timezone import utc class SetCookieTests(SimpleTestCase): @@ -18,7 +17,9 @@ class SetCookieTests(SimpleTestCase): # evaluated expiration time and the time evaluated in set_cookie(). If # this difference doesn't exist, the cookie time will be 1 second # larger. The sleep guarantees that there will be a time difference. - expires = datetime.now(tz=utc).replace(tzinfo=None) + timedelta(seconds=10) + expires = datetime.now(tz=timezone.utc).replace(tzinfo=None) + timedelta( + seconds=10 + ) time.sleep(0.001) response.set_cookie("datetime", expires=expires) datetime_cookie = response.cookies["datetime"] @@ -27,7 +28,7 @@ class SetCookieTests(SimpleTestCase): def test_aware_expiration(self): """set_cookie() accepts an aware datetime as expiration time.""" response = HttpResponse() - expires = datetime.now(tz=utc) + timedelta(seconds=10) + expires = datetime.now(tz=timezone.utc) + timedelta(seconds=10) time.sleep(0.001) response.set_cookie("datetime", expires=expires) datetime_cookie = response.cookies["datetime"] diff --git a/tests/schema/tests.py b/tests/schema/tests.py index 076663e049..d9e59d32dc 100644 --- a/tests/schema/tests.py +++ b/tests/schema/tests.py @@ -55,7 +55,6 @@ from django.db.models.indexes import IndexExpression from django.db.transaction import TransactionManagementError, atomic from django.test import TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext, isolate_apps, register_lookup -from django.utils import timezone from .fields import CustomManyToManyField, InheritedManyToManyField, MediumBlobField from .models import ( @@ -4231,7 +4230,7 @@ class SchemaTests(TransactionTestCase): """ now = datetime.datetime(month=1, day=1, year=2000, hour=1, minute=1) now_tz = datetime.datetime( - month=1, day=1, year=2000, hour=1, minute=1, tzinfo=timezone.utc + month=1, day=1, year=2000, hour=1, minute=1, tzinfo=datetime.timezone.utc ) mocked_datetime.now = mock.MagicMock(return_value=now) mocked_tz.now = mock.MagicMock(return_value=now_tz) diff --git a/tests/staticfiles_tests/storage.py b/tests/staticfiles_tests/storage.py index 1bb4e37485..51614fbb18 100644 --- a/tests/staticfiles_tests/storage.py +++ b/tests/staticfiles_tests/storage.py @@ -1,10 +1,9 @@ import os -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from django.conf import settings from django.contrib.staticfiles.storage import ManifestStaticFilesStorage from django.core.files import storage -from django.utils import timezone class DummyStorage(storage.Storage): diff --git a/tests/staticfiles_tests/test_management.py b/tests/staticfiles_tests/test_management.py index 09ce7c488c..6dec3a67bd 100644 --- a/tests/staticfiles_tests/test_management.py +++ b/tests/staticfiles_tests/test_management.py @@ -17,7 +17,6 @@ from django.core.management import CommandError, call_command from django.core.management.base import SystemCheckError from django.test import RequestFactory, override_settings from django.test.utils import extend_sys_path -from django.utils import timezone from django.utils._os import symlinks_supported from django.utils.functional import empty @@ -531,7 +530,7 @@ class TestCollectionNonLocalStorage(TestNoFilesCreated, CollectionTestCase): storage = DummyStorage() self.assertEqual( storage.get_modified_time("name"), - datetime.datetime(1970, 1, 1, tzinfo=timezone.utc), + datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc), ) with self.assertRaisesMessage( NotImplementedError, "This backend doesn't support absolute paths." diff --git a/tests/timezones/tests.py b/tests/timezones/tests.py index 75c79ecfdd..4e26516041 100644 --- a/tests/timezones/tests.py +++ b/tests/timezones/tests.py @@ -75,7 +75,7 @@ except ImportError: # datetime.datetime(2011, 9, 1, 13, 20, 30), which translates to # 10:20:30 in UTC and 17:20:30 in ICT. -UTC = timezone.utc +UTC = datetime.timezone.utc EAT = timezone.get_fixed_timezone(180) # Africa/Nairobi ICT = timezone.get_fixed_timezone(420) # Asia/Bangkok @@ -651,7 +651,7 @@ class NewDatabaseTests(TestCase): @skipIfDBFeature("supports_timezones") def test_cursor_execute_accepts_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) - utc_naive_dt = timezone.make_naive(dt, timezone.utc) + utc_naive_dt = timezone.make_naive(dt, datetime.timezone.utc) with connection.cursor() as cursor: cursor.execute( "INSERT INTO timezones_event (dt) VALUES (%s)", [utc_naive_dt] @@ -670,7 +670,7 @@ class NewDatabaseTests(TestCase): @skipIfDBFeature("supports_timezones") def test_cursor_execute_returns_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) - utc_naive_dt = timezone.make_naive(dt, timezone.utc) + utc_naive_dt = timezone.make_naive(dt, datetime.timezone.utc) Event.objects.create(dt=dt) with connection.cursor() as cursor: cursor.execute( diff --git a/tests/utils_tests/test_dateformat.py b/tests/utils_tests/test_dateformat.py index 4e4926c85b..4402048f3a 100644 --- a/tests/utils_tests/test_dateformat.py +++ b/tests/utils_tests/test_dateformat.py @@ -1,15 +1,10 @@ -from datetime import date, datetime, time, tzinfo +from datetime import date, datetime, time, timezone, tzinfo from django.test import SimpleTestCase, override_settings from django.test.utils import TZ_SUPPORT, requires_tz_support from django.utils import dateformat, translation from django.utils.dateformat import format -from django.utils.timezone import ( - get_default_timezone, - get_fixed_timezone, - make_aware, - utc, -) +from django.utils.timezone import get_default_timezone, get_fixed_timezone, make_aware @override_settings(TIME_ZONE="Europe/Copenhagen") @@ -71,7 +66,7 @@ class DateFormatTests(SimpleTestCase): ) def test_epoch(self): - udt = datetime(1970, 1, 1, tzinfo=utc) + udt = datetime(1970, 1, 1, tzinfo=timezone.utc) self.assertEqual(format(udt, "U"), "0") def test_empty_format(self): @@ -216,7 +211,7 @@ class DateFormatTests(SimpleTestCase): @requires_tz_support def test_e_format_with_named_time_zone(self): - dt = datetime(1970, 1, 1, tzinfo=utc) + dt = datetime(1970, 1, 1, tzinfo=timezone.utc) self.assertEqual(dateformat.format(dt, "e"), "UTC") @requires_tz_support diff --git a/tests/utils_tests/test_feedgenerator.py b/tests/utils_tests/test_feedgenerator.py index 90deb2ddf2..ee15b6e928 100644 --- a/tests/utils_tests/test_feedgenerator.py +++ b/tests/utils_tests/test_feedgenerator.py @@ -2,7 +2,7 @@ import datetime from django.test import SimpleTestCase from django.utils import feedgenerator -from django.utils.timezone import get_fixed_timezone, utc +from django.utils.timezone import get_fixed_timezone class FeedgeneratorTests(SimpleTestCase): @@ -144,4 +144,7 @@ class FeedgeneratorTests(SimpleTestCase): for use_tz in (True, False): with self.settings(USE_TZ=use_tz): rss_feed = feedgenerator.Rss201rev2Feed("title", "link", "description") - self.assertEqual(rss_feed.latest_post_date().tzinfo, utc) + self.assertEqual( + rss_feed.latest_post_date().tzinfo, + datetime.timezone.utc, + )