Skip to content

DeprecationWarning: datetime.datetime.utcnow() is deprecated in Python 3.12+ #332

@libre-man

Description

@libre-man

When running python-saml on Python 3.12, a DeprecationWarning is triggered during the authentication process. This occurs because datetime.datetime.utcnow() has been deprecated in favor of timezone-aware objects.

While this is currently only a warning, it is scheduled for removal in future Python versions and litters the logs of applications using this toolkit on modern Python environments.

Traceback / Warning:

  File ".../onelogin/saml2/auth.py", line 419, in login
    authn_request = self.authn_request_class(self._settings, force_authn, is_passive, set_nameid_policy, name_id_value_req)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".../onelogin/saml2/authn_request.py", line 49, in __init__
    issue_instant = OneLogin_Saml2_Utils.parse_time_to_SAML(OneLogin_Saml2_Utils.now())
                                                           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".../onelogin/saml2/utils.py", line 428, in now
    return calendar.timegm(datetime.utcnow().utctimetuple())
                           ^^^^^^^^^^^^^^^^^
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).

Affected Code:

The issue is located in the now() static method of the OneLogin_Saml2_Utils class:

return calendar.timegm(datetime.utcnow().utctimetuple())

Suggested Resolution:

Update the now() method to use a timezone-aware UTC datetime. For backwards compatibility with older Python 3 versions, datetime.now(timezone.utc) is the standard approach:

from datetime import datetime, timezone

# ...

@staticmethod
def now():
    return calendar.timegm(datetime.now(timezone.utc).utctimetuple())

Environment:

  • Python Version: 3.12+
  • Library: python-saml / python3-saml

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions