PYTHON-3702 Stop using utcnow and utcfromtimestamp (#1229)

This commit is contained in:
Noah Stapp 2023-06-12 15:43:30 -07:00 committed by GitHub
parent 3f687f71fb
commit ec3437849e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 21 additions and 17 deletions

View File

@ -26,7 +26,7 @@ from bson.codec_options import DEFAULT_CODEC_OPTIONS, CodecOptions, DatetimeConv
from bson.tz_util import utc
EPOCH_AWARE = datetime.datetime.fromtimestamp(0, utc)
EPOCH_NAIVE = datetime.datetime.utcfromtimestamp(0)
EPOCH_NAIVE = datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc).replace(tzinfo=None)
class DatetimeMS:

View File

@ -25,10 +25,12 @@ time into MongoDB:
.. doctest::
>>> result = db.objects.insert_one({"last_modified": datetime.datetime.utcnow()})
>>> result = db.objects.insert_one(
... {"last_modified": datetime.datetime.now(tz=timezone.utc)}
... )
Always use :meth:`datetime.datetime.utcnow`, which returns the current time in
UTC, instead of :meth:`datetime.datetime.now`, which returns the current local
Always use :meth:`datetime.datetime.now(tz=timezone.utc)`, which explicitly returns the current time in
UTC, instead of :meth:`datetime.datetime.now`, with no arguments, which returns the current local
time. Avoid doing this:
.. doctest::

View File

@ -109,7 +109,7 @@ post:
... "author": "Mike",
... "text": "My first blog post!",
... "tags": ["mongodb", "python", "pymongo"],
... "date": datetime.datetime.utcnow(),
... "date": datetime.datetime.now(tz=timezone.utc),
... }
Note that documents can contain native Python types (like

View File

@ -292,7 +292,7 @@ class GridIn:
self.__flush_buffer()
# The GridFS spec says length SHOULD be an Int64.
self._file["length"] = Int64(self._position)
self._file["uploadDate"] = datetime.datetime.utcnow()
self._file["uploadDate"] = datetime.datetime.now(tz=datetime.timezone.utc)
return self._coll.files.insert_one(self._file, session=self._session)
except DuplicateKeyError:

View File

@ -16,6 +16,7 @@
from collections import namedtuple
from datetime import datetime as _datetime
from datetime import timezone
from pymongo.lock import _create_lock
@ -60,7 +61,7 @@ class _OCSPCache:
return
# Do nothing if the response is invalid.
if not (value.this_update <= _datetime.utcnow() < value.next_update):
if not (value.this_update <= _datetime.now(tz=timezone.utc) < value.next_update):
return
# Cache new response OR update cached response if new response
@ -81,7 +82,7 @@ class _OCSPCache:
value = self._data[cache_key]
# Return cached response if it is still valid.
if value.this_update <= _datetime.utcnow() < value.next_update:
if value.this_update <= _datetime.now(tz=timezone.utc) < value.next_update:
return value
self._data.pop(cache_key, None)

View File

@ -17,6 +17,7 @@
import logging as _logging
import re as _re
from datetime import datetime as _datetime
from datetime import timezone
from cryptography.exceptions import InvalidSignature as _InvalidSignature
from cryptography.hazmat.backends import default_backend as _default_backend
@ -219,7 +220,7 @@ def _verify_response(issuer, response):
# Note that we are not using a "tolerance period" as discussed in
# https://tools.ietf.org/rfc/rfc5019.txt?
now = _datetime.utcnow()
now = _datetime.now(tz=timezone.utc)
# RFC6960, Section 3.2, Number 5
if response.this_update > now:
_LOGGER.debug("thisUpdate is in the future")

View File

@ -986,7 +986,7 @@ class TestCodecOptions(unittest.TestCase):
def test_decode_all_defaults(self):
# Test decode_all()'s default document_class is dict and tz_aware is
# False.
doc = {"sub_document": {}, "dt": datetime.datetime.utcnow()}
doc = {"sub_document": {}, "dt": datetime.datetime.now(tz=datetime.timezone.utc)}
decoded = bson.decode_all(bson.encode(doc))[0]
self.assertIsInstance(decoded["sub_document"], dict)
@ -998,7 +998,7 @@ class TestCodecOptions(unittest.TestCase):
def test_decode_all_no_options(self):
# Test decode_all()'s default document_class is dict and tz_aware is
# False.
doc = {"sub_document": {}, "dt": datetime.datetime.utcnow()}
doc = {"sub_document": {}, "dt": datetime.datetime.now(tz=datetime.timezone.utc)}
decoded = bson.decode_all(bson.encode(doc), None)[0]
self.assertIsInstance(decoded["sub_document"], dict)

View File

@ -1143,7 +1143,7 @@ class TestClient(IntegrationTest):
naive = self.client
aware.pymongo_test.drop_collection("test")
now = datetime.datetime.utcnow()
now = datetime.datetime.now(tz=datetime.timezone.utc)
aware.pymongo_test.test.insert_one({"x": now})
self.assertEqual(None, naive.pymongo_test.test.find_one()["x"].tzinfo)

View File

@ -86,7 +86,7 @@ class TestObjectId(unittest.TestCase):
self.assertEqual(a, ObjectId(str(a)))
def test_generation_time(self):
d1 = datetime.datetime.utcnow()
d1 = datetime.datetime.now(tz=datetime.timezone.utc).replace(tzinfo=None)
d2 = ObjectId().generation_time
self.assertEqual(utc, d2.tzinfo)
@ -97,7 +97,7 @@ class TestObjectId(unittest.TestCase):
if "PyPy 1.8.0" in sys.version:
# See https://bugs.pypy.org/issue1092
raise SkipTest("datetime.timedelta is broken in pypy 1.8.0")
d = datetime.datetime.utcnow()
d = datetime.datetime.now(tz=datetime.timezone.utc).replace(tzinfo=None)
d = d - datetime.timedelta(microseconds=d.microsecond)
oid = ObjectId.from_datetime(d)
self.assertEqual(d, oid.generation_time.replace(tzinfo=None))

View File

@ -17,7 +17,7 @@
import random
import sys
from collections import namedtuple
from datetime import datetime, timedelta
from datetime import datetime, timedelta, timezone
from os import urandom
from time import sleep
from typing import Any
@ -61,7 +61,7 @@ class TestOcspCache(unittest.TestCase):
)
def _create_mock_response(self, this_update_delta_seconds, next_update_delta_seconds):
now = datetime.utcnow()
now = datetime.now(tz=timezone.utc)
this_update = now + timedelta(seconds=this_update_delta_seconds)
if next_update_delta_seconds is not None:
next_update = now + timedelta(seconds=next_update_delta_seconds)

View File

@ -44,7 +44,7 @@ def get_addresses(server_list):
def make_last_write_date(server):
epoch = datetime.datetime.utcfromtimestamp(0)
epoch = datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc).replace(tzinfo=None)
millis = server.get("lastWrite", {}).get("lastWriteDate")
if millis:
diff = ((millis % 1000) + 1000) % 1000