numpy / numpy/numpy

add datetime64.__format__ similar to datetime.__format__

Open
#17,177 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

01 - Enhancement component: numpy.datetime64
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.