为何无法忽略datetime.datetime.utcnow()的DeprecationWarning?
解决Python 3.12中无法压制
datetime.utcnow()弃用警告的问题 你遇到的问题核心是精确匹配完整警告消息字符串的方式过于脆弱,容易因为消息的细微格式差异导致过滤规则不生效。以下是具体原因和解决方案:
为什么原代码不生效
datetime.utcnow()的弃用警告是从C扩展模块发出的,虽然你写的消息字符串看起来和实际警告一致,但Python的warnings.filterwarnings默认使用fnmatch风格的通配符匹配,而非完全精确的字符串比对——如果实际消息和你写的字符串有任何细微差异(比如隐式的空格、版本迭代带来的消息微调),都会导致匹配失败。
另外,未指定警告来源模块datetime,也可能让规则的针对性变弱,甚至被其他设置干扰。
可靠的解决方案
方案1:匹配消息核心内容(fnmatch通配符)
只匹配警告消息的开头部分,用通配符覆盖后续内容,同时指定来源模块确保只过滤datetime模块的这个警告:
import warnings import datetime warnings.filterwarnings( action="ignore", message="datetime.datetime.utcnow() is deprecated*", category=DeprecationWarning, module="datetime" ) datetime.datetime.utcnow()
方案2:正则表达式匹配(更灵活)
如果需要更精确的匹配,可以启用正则表达式模式,匹配消息中的关键片段:
import warnings import datetime warnings.filterwarnings( action="ignore", message=r".*datetime\.datetime\.utcnow\(\) is deprecated and scheduled for removal.*", category=DeprecationWarning, module="datetime", regex=True ) datetime.datetime.utcnow()
调试技巧:确认警告的实际参数
如果还是不确定问题出在哪,可以先自定义showwarning函数,打印警告的所有细节,再调整过滤规则:
import warnings import datetime def debug_showwarning(message, category, filename, lineno, file=None, line=None): print(f"警告消息:{message}") print(f"警告类别:{category.__name__}") print(f"来源模块:{filename}") warnings.showwarning = debug_showwarning datetime.datetime.utcnow()
运行后你会看到警告的完整参数,照着这些参数写过滤规则就不会出错。
内容的提问来源于stack exchange,提问作者rrauenza
相关产品推荐
相关产品推荐

