Given an array of datetimes, return the same dates in another cftime or numpy date type. Useful to convert between calendars in numpy and cftime or between cftime calendars. If raise_on_valid is True (default), invalid dates trigger a ValueError. Otherwise, the invalid element is repla
(times, date_type, raise_on_invalid: bool = True)
| 836 | |
| 837 | |
| 838 | def convert_times(times, date_type, raise_on_invalid: bool = True) -> np.ndarray: |
| 839 | """Given an array of datetimes, return the same dates in another cftime or numpy date type. |
| 840 | |
| 841 | Useful to convert between calendars in numpy and cftime or between cftime calendars. |
| 842 | |
| 843 | If raise_on_valid is True (default), invalid dates trigger a ValueError. |
| 844 | Otherwise, the invalid element is replaced by np.nan for cftime types and np.NaT for np.datetime64. |
| 845 | """ |
| 846 | if date_type in (pd.Timestamp, np.datetime64) and not is_np_datetime_like( |
| 847 | times.dtype |
| 848 | ): |
| 849 | return cftime_to_nptime(times, raise_on_invalid=raise_on_invalid) |
| 850 | if is_np_datetime_like(times.dtype): |
| 851 | # Convert datetime64 objects to Timestamps since those have year, month, day, etc. attributes |
| 852 | times = pd.DatetimeIndex(times) |
| 853 | new = np.empty(times.shape, dtype="O") |
| 854 | for i, t in enumerate(times): |
| 855 | try: |
| 856 | dt = date_type( |
| 857 | t.year, t.month, t.day, t.hour, t.minute, t.second, t.microsecond |
| 858 | ) |
| 859 | except ValueError as e: |
| 860 | if raise_on_invalid: |
| 861 | raise ValueError( |
| 862 | f"Cannot convert date {t} to a date in the " |
| 863 | f"{date_type(2000, 1, 1).calendar} calendar. Reason: {e}." |
| 864 | ) from e |
| 865 | else: |
| 866 | dt = np.nan |
| 867 | |
| 868 | new[i] = dt |
| 869 | return new |
| 870 | |
| 871 | |
| 872 | def convert_time_or_go_back(date, date_type): |
no test coverage detected
searching dependent graphs…