Open
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.