1
0
mirror of https://github.com/django/django.git synced 2024-12-22 00:55:44 +00:00

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.
This commit is contained in:
Carlton Gibson 2022-03-23 12:15:36 +01:00 committed by Mariusz Felisiak
parent 1cf60ce601
commit bb61f0186d
33 changed files with 115 additions and 102 deletions

View File

@ -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:

View File

@ -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):

View File

@ -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)

View File

@ -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(

View File

@ -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

View File

@ -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"])

View File

@ -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

View File

@ -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).

View File

@ -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")

View File

@ -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<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\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

View File

@ -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:

View File

@ -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

View File

@ -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.

View File

@ -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.

View File

@ -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)

View File

@ -151,7 +151,7 @@ used.
However, :ref:`as explained above <naive-datetime-objects>`, 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
-------------------------------

View File

@ -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"),

View File

@ -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

View File

@ -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):

View File

@ -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(

View File

@ -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)

View File

@ -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:

View File

@ -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)

View File

@ -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",

View File

@ -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):

View File

@ -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])

View File

@ -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"]

View File

@ -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)

View File

@ -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):

View File

@ -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."

View File

@ -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(

View File

@ -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

View File

@ -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,
)