Skip to content

datetime module should provide timezone awareness checks #111177

@jakob-keller

Description

@jakob-keller

Feature or enhancement

Proposal:

Situation

Documentation of the datetime module states that:

Date and time objects may be categorized as “aware” or “naive” depending on whether or not they include timezone information.

Documentation of the datetime module also defines how to determine if an object is aware or naive.

This check needs to be performed frequently in application code, e.g. as part of input validation and/or normalization.

Multiple third-party packages implement awareness checks and helpers:

As of now, no such checks are offered by the Python standard library.

Problem

Any Python user that needs to check for timezone awareness needs to either implement the checks herself or rely on third-party libraries. This is more cumbersome than it needs to be.

Solution

The Python standard library should offer timezone awareness checks as part of the datetime module.

There are several implementation options available, including:

  1. is_naive(__obj) and/or is_aware(__obj) helper functions
  2. is_naive and/or is_aware properties on the level of "date and time objects"

While 1.) is typically followed by third-party packages, IMO Python should implement 2.) as part of the datetime module.

Proposed API:

import datetime

# `datetime.date` objects
d = datetime.date.today()
assert d.is_naive is True
assert d.is_aware is False

# `datetime.datetime` objects
naive_dt = datetime.datetime.now()
assert naive_dt.is_naive is True
assert naive_dt.is_aware is False

aware_dt = datetime.datetime.now(tz=datetime.timezone.utc)
assert aware_dt.is_naive is False
assert aware_dt.is_aware is True

# `datetime.time` objects
naive_t = naive_dt.time()
assert naive_t.is_naive is True
assert naive_t.is_aware is False

aware_t = aware_dt.timetz()
assert aware_t.is_naive is False
assert aware_t.is_aware is True

The signature of these proposed is_naive and is_aware properties may optionally be specified as a typing.Protocol.

I could try to prepare a PR, if there is sufficient interest.

What do you think?

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions