Skip to content

DOC: Document datetime and timedelta to python's object type conversion #29557

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

devmt04
Copy link

@devmt04 devmt04 commented Aug 13, 2025

The need to document datetime and timedelta to Python object type conversions arose during a discussion in issue #29516

NumPy follows a strict type conversion protocol when converting datetime64 or timedelta64 to standard Python objects. The rules are as follows:

Conversion of datetime64 to Python objects

  • Not-a-time is returned as None.
  • For days or coarser, returns a datetime.date.
  • For microseconds or coarser, returns a datetime.datetime.
  • For units finer than microseconds, returns an integer.

Conversion of timedelta64 to Python objects

  • Not-a-time is returned as None.
  • For microseconds or coarser, returns a datetime.timedelta.
  • For Y/M/B (nonlinear units), generic units and units finer than microseconds, returns an integer.

Currently, this behavior is not clearly documented, which can lead to ambiguity for end users, forcing them to infer the conversion rules through experimentation.

Comment on lines 327 to 328
- For microseconds or coarser, returns a datetime.timedelta.
- For units finer than microseconds, returns an integer.
Copy link
Member

@jorenham jorenham Aug 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

months, years, and unit-less timedelta's also return integers:

>>> import numpy as np
>>> np.timedelta64(1, "M").item()
1
>>> np.timedelta64(1, "Y").item()
1
>>> np.timedelta64(1).item()
1

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Solved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants