iris icon indicating copy to clipboard operation
iris copied to clipboard

Provide a neat way to get date strings from arrays with date units.

Open pp-mo opened this issue 4 years ago • 6 comments

✨ Feature Request

Following [this comment] https://github.com/SciTools/iris/pull/4499#issuecomment-1012947187 (and preceding ones).

If you know what you're doing this isn't actually that hard. E.G. coord.units.num2date(coord.bounds).astype('str') But it isn't so easy to work that out.

How about Coord.date_strings() ?
We can make it cheekily default to the Coord's own points, like Connectivity.indices_by_src

pp-mo avatar Jan 17 '22 15:01 pp-mo

I wanted this again today. I think the implementation is easy, and the hard bit is deciding what the interface should be. So marking this for discussion.

rcomer avatar Dec 13 '22 16:12 rcomer

One option which seemed favourable in peloton discussions: adding a __format__ method to Coord, such that format(tcoord, "%Y-%m-%d") could be used to create a string with all points formatted with the given format string. This is also used by f-strings so f"{tcoord:%Y-%m-%d}" would be equivalent.

Actual implementation might look something like

def __format__(self, fmt):
    return str([format(point, fmt) for point in self.units.num2date(self.points)])

Just needs a bit more thought into points vs bounds (always both? extra symbol in the fmt string to choose one or the other?)

vsherratt avatar Dec 14 '22 10:12 vsherratt

As one immediately upvoting this feature I am really looking forward to this, and I would very much favour the possibility to choose only points, only bounds, or both. Many thanks /L

larsbarring avatar Dec 14 '22 10:12 larsbarring

I wanted this again today so I rolled my own

def print_coord_times(coord, points=True, bounds=True):
    """
    Given a time type coordinate (e.g. 'time' or 'forecast_reference_time'),
    print string representations of the points/bounds.

    Set *points* or *bounds* to False to skip printing those.
    """
    if not coord.units.is_time_reference():
        raise ValueError(f"{coord.name()} is not a time type coordinate")

    if points:
        print("Points:")
        print(coord.units.num2date(coord.points).astype('str'))

    if bounds:
        print("Bounds:")
        print(coord.units.num2date(coord.bounds).astype('str'))

rcomer avatar Jan 17 '24 18:01 rcomer