Convert a single date to a new date_type (cftime.datetime or pd.Timestamp). If the new date is invalid, it goes back a day and tries again. If it is still invalid, goes back a second day. This is meant to convert end-of-month dates into a new calendar.
(date, date_type)
| 870 | |
| 871 | |
| 872 | def convert_time_or_go_back(date, date_type): |
| 873 | """Convert a single date to a new date_type (cftime.datetime or pd.Timestamp). |
| 874 | |
| 875 | If the new date is invalid, it goes back a day and tries again. If it is still |
| 876 | invalid, goes back a second day. |
| 877 | |
| 878 | This is meant to convert end-of-month dates into a new calendar. |
| 879 | """ |
| 880 | if date_type == pd.Timestamp: |
| 881 | date_type = default_precision_timestamp |
| 882 | try: |
| 883 | return date_type( |
| 884 | date.year, |
| 885 | date.month, |
| 886 | date.day, |
| 887 | date.hour, |
| 888 | date.minute, |
| 889 | date.second, |
| 890 | date.microsecond, |
| 891 | ) |
| 892 | except OutOfBoundsDatetime: |
| 893 | raise |
| 894 | except ValueError: |
| 895 | # Day is invalid, happens at the end of months, try again the day before |
| 896 | try: |
| 897 | return date_type( |
| 898 | date.year, |
| 899 | date.month, |
| 900 | date.day - 1, |
| 901 | date.hour, |
| 902 | date.minute, |
| 903 | date.second, |
| 904 | date.microsecond, |
| 905 | ) |
| 906 | except ValueError: |
| 907 | # Still invalid, happens for 360_day to non-leap february. Try again 2 days before date. |
| 908 | return date_type( |
| 909 | date.year, |
| 910 | date.month, |
| 911 | date.day - 2, |
| 912 | date.hour, |
| 913 | date.minute, |
| 914 | date.second, |
| 915 | date.microsecond, |
| 916 | ) |
| 917 | |
| 918 | |
| 919 | def _should_cftime_be_used( |
no test coverage detected
searching dependent graphs…