Skip to content

Commit b87a67c

Browse files
authored
Merge b489e1d into 0fdedb4
2 parents 0fdedb4 + b489e1d commit b87a67c

File tree

4 files changed

+417
-385
lines changed

4 files changed

+417
-385
lines changed

lib/iris/common/metadata.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from collections import namedtuple
1111
from collections.abc import Iterable, Mapping
1212
from copy import deepcopy
13+
from datetime import timedelta
1314
from functools import lru_cache, wraps
1415
import re
1516
from typing import TYPE_CHECKING, Any
@@ -54,6 +55,37 @@
5455
logger = get_logger(__name__, fmt="[%(cls)s.%(funcName)s]")
5556

5657

58+
_num2date_original = cf_units.Unit.num2date
59+
60+
61+
def _num2date_to_nearest_second(
62+
self,
63+
time_value,
64+
only_use_cftime_datetimes=True,
65+
only_use_python_datetimes=False,
66+
):
67+
def _round(date):
68+
if date.microsecond == 0:
69+
return date
70+
elif date.microsecond < 500000:
71+
return date - timedelta(microseconds=date.microsecond)
72+
else:
73+
return date + timedelta(seconds=1) - timedelta(microseconds=date.microsecond)
74+
75+
dates = _num2date_original(
76+
self, time_value, only_use_cftime_datetimes, only_use_python_datetimes
77+
)
78+
if hasattr(dates, "shape"):
79+
vfunc = np.vectorize(_round)
80+
result = vfunc(dates)
81+
else:
82+
result = _round(dates)
83+
return result
84+
85+
86+
cf_units.Unit.num2date = _num2date_to_nearest_second
87+
88+
5789
def hexdigest(item):
5890
"""Calculate a hexadecimal string hash representation of the provided item.
5991

0 commit comments

Comments
 (0)