Given an array of cftime.datetime objects, return an array of numpy.datetime64 objects of the same size If raise_on_invalid is True (default), invalid dates trigger a ValueError. Otherwise, the invalid element is replaced by np.NaT.
(
times, raise_on_invalid: bool = True, time_unit: PDDatetimeUnitOptions = "ns"
)
| 806 | |
| 807 | |
| 808 | def cftime_to_nptime( |
| 809 | times, raise_on_invalid: bool = True, time_unit: PDDatetimeUnitOptions = "ns" |
| 810 | ) -> np.ndarray: |
| 811 | """Given an array of cftime.datetime objects, return an array of |
| 812 | numpy.datetime64 objects of the same size |
| 813 | |
| 814 | If raise_on_invalid is True (default), invalid dates trigger a ValueError. |
| 815 | Otherwise, the invalid element is replaced by np.NaT.""" |
| 816 | times = np.asarray(times) |
| 817 | new = [] |
| 818 | dt: np.datetime64 |
| 819 | for _i, t in np.ndenumerate(times): |
| 820 | try: |
| 821 | # We expect either "us" resolution or "s" resolution depending on |
| 822 | # whether 'microseconds' are defined for the input or not. |
| 823 | dt = ( |
| 824 | pd.Timestamp(np.datetime64(t.isoformat())).as_unit(time_unit).to_numpy() |
| 825 | ) |
| 826 | except ValueError as e: |
| 827 | if raise_on_invalid: |
| 828 | raise ValueError( |
| 829 | f"Cannot convert date {t} to a date in the " |
| 830 | f"standard calendar. Reason: {e}." |
| 831 | ) from e |
| 832 | else: |
| 833 | dt = np.datetime64("NaT", time_unit) |
| 834 | new.append(dt) |
| 835 | return np.asarray(new).reshape(times.shape) |
| 836 | |
| 837 | |
| 838 | def convert_times(times, date_type, raise_on_invalid: bool = True) -> np.ndarray: |
searching dependent graphs…