-
-
Notifications
You must be signed in to change notification settings - Fork 34.2k
Description
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:
Django: https://docs.djangoproject.com/en/4.2/ref/utils/#django.utils.timezone.is_awarepeprock: https://github.com/Ponte-Energy-Partners/peprock/blob/main/peprock/datetime/awareness.py (disclaimer: I'm the author ofpeprock)- ...
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:
is_naive(__obj)and/oris_aware(__obj)helper functionsis_naiveand/oris_awareproperties 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 TrueThe 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
Labels
Projects
Status