Skip to content

Commit b82227e

Browse files
committed
Replace deprecated datetime.utcnow() with timezone-aware equivalent
`datetime.datetime.utcnow()` is deprecated since Python 3.12 and scheduled for removal in a future version: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC). `datetime_to_datestamp()` in `oaipmh/datestamp.py` asserts that the input has `tzinfo is None`, so we convert the timezone-aware UTC value back to naive with `.replace(tzinfo=None)` before passing it in. The resulting `responseDate` string in the OAI-PMH response is unchanged. This is the only `datetime.utcnow()` call in the codebase; after this change, pyoai no longer emits `DeprecationWarning` for it on Python 3.12+.
1 parent ac4a79f commit b82227e

1 file changed

Lines changed: 6 additions & 2 deletions

File tree

src/oaipmh/server.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from lxml.etree import ElementTree, Element, SubElement
22
from lxml import etree
3-
from datetime import datetime
3+
from datetime import datetime, timezone
44
try:
55
from urllib.parse import urlencode, quote, unquote
66
except ImportError:
@@ -173,8 +173,12 @@ def _outputBasicEnvelope(self, **kw):
173173
e_tree = ElementTree(element=e_oaipmh)
174174
e_responseDate = SubElement(e_oaipmh, nsoai('responseDate'))
175175
# date should be first possible moment
176+
# datetime.utcnow() is deprecated since Python 3.12 and scheduled
177+
# for removal. datetime_to_datestamp() requires a naive datetime
178+
# (it asserts dt.tzinfo is None), so convert the aware UTC
179+
# value back to naive before passing it in.
176180
e_responseDate.text = datetime_to_datestamp(
177-
datetime.utcnow().replace(microsecond=0))
181+
datetime.now(timezone.utc).replace(microsecond=0, tzinfo=None))
178182
e_request = SubElement(e_oaipmh, nsoai('request'))
179183
for key, value in kw.items():
180184
if key == 'from_':

0 commit comments

Comments
 (0)