deprecation-warningpython-3.12

Why can't I ignore this "datetime.datetime.utcnow()" DeprecationWarning?


I can't seem to suppress this deprecation warning. Normally in unit tests I force warnings to errors, and then ignore them if unfixable in current stack. I'm currently using Python 3.12.1

Here is code to reproduce:

import warnings
import datetime

# warnings.simplefilter('error')
warnings.filterwarnings(action="ignore", message="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).", category=DeprecationWarning)
datetime.datetime.utcnow()

Running this, I get:

$ python3.12 /tmp/foo.py
/tmp/foo.py:7: 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.datetime.utcnow()

I also tried editing warnings.py in the python3.12.1 source tree and then realized that since utcnow() is a C module underneath, it just calls directly into _warnings.c in python. So it isn't traceable in python. I've attached gdb and did a break on warn_explicit, but haven't figured out yet how to examine the strings inside the PyObject.

Is there something obvious or non obvious I'm doing wrong here?


Solution

  • As the comment by @jhasonharper in the question mentions, message is actually a regex:

    This checks the types of the arguments, compiles the message and module regular expressions, and inserts them as a tuple in the list of warnings filters.

    This is enough to catch the warning:

    warnings.filterwarnings(action="ignore", message=r"datetime.datetime.utcnow")
    

    This also works:

    warnings.filterwarnings(action="ignore", 
      message=r"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\).")