add datetime64.__format__ similar to datetime.__format__
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 32.8k
- Forks
- 12.8k
- Avg merge
- 1d 7h
- Merged PRs (30d)
- 197
Description
I would like for np.datetime64 to support the format-specification language using the __format__ method, so that it can be used in formatting strings. I frequently want to format plot labels using datetimes extracted from time coordinates in xarray.DataArray objects. Those have dtype M8[ns]. To format the date in a string directly, I need to convert these to datetime.datetime — due to the precision (see #12550) I need to manually cast to a lower time-resolution first. So rather than f'{d:%Y}' I need to write f'{d.astype("M8[s]").astype(datetime.datetime):%Y}, which is somewhat cumbersome.
Reproducing code example:
import numpy as np
d = np.datetime64(1234567890987654321, "ns")
print(f"{d:%Y}")
Error message:
Traceback (most recent call last):
File "mwe84.py", line 3, in <module>
print(f"{d:%Y}")
ValueError: Invalid format specifier
Numpy/Python version information:
Numpy 1.19.1, Python 3.8.5.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
No source file or test is named. Start by running the supplied np.datetime64 example and inspect the existing datetime formatting behavior and datetime64 implementation. Done means format specifications such as %Y work directly in an f-string for datetime64 values, including the shown nanosecond value.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- data
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100