|
| 1 | +import datetime |
| 2 | +from dateutil.relativedelta import relativedelta |
| 3 | +from calendar import monthrange, isleap |
| 4 | + |
| 5 | + |
| 6 | +class MpasRelativeDelta(relativedelta): |
| 7 | + """ |
| 8 | + MpasRelativeDelta is a subclass of dateutil.relativedelta for relative time |
| 9 | + intervals with different MPAS calendars. |
| 10 | +
|
| 11 | + Only relative intervals (years, months, etc.) are supported and not the |
| 12 | + absolute date specifications (year, month, etc.). Addition/subtraction |
| 13 | + of datetime.datetime objects or other MpasRelativeDelta (but currently not |
| 14 | + datetime.date, datetime.timedelta or other related objects) is supported. |
| 15 | +
|
| 16 | + Author |
| 17 | + ------ |
| 18 | + Xylar Asay-Davis |
| 19 | +
|
| 20 | + Last Modified |
| 21 | + ------------- |
| 22 | + 02/09/2017 |
| 23 | + """ |
| 24 | + |
| 25 | + def __init__(self, dt1=None, dt2=None, years=0, months=0, days=0, |
| 26 | + hours=0, minutes=0, seconds=0, calendar='gregorian'): |
| 27 | + if calendar not in ['gregorian', 'gregorian_noleap']: |
| 28 | + raise ValueError('Unsupported MPAs calendar {}'.format(calendar)) |
| 29 | + self.calendar = calendar |
| 30 | + super(MpasRelativeDelta, self).__init__(dt1=dt1, dt2=dt2, years=years, |
| 31 | + months=months, days=days, |
| 32 | + hours=hours, minutes=minutes, |
| 33 | + seconds=seconds) |
| 34 | + |
| 35 | + def __add__(self, other): |
| 36 | + if not isinstance(other, (datetime.datetime, MpasRelativeDelta)): |
| 37 | + return NotImplemented |
| 38 | + |
| 39 | + if isinstance(other, MpasRelativeDelta): |
| 40 | + if self.calendar != other.calendar: |
| 41 | + raise ValueError('MpasRelativeDelta objects can only be added ' |
| 42 | + 'if their calendars match.') |
| 43 | + years = self.years + other.years |
| 44 | + months = self.months + other.months |
| 45 | + if months > 12: |
| 46 | + years += 1 |
| 47 | + months -= 12 |
| 48 | + elif months < 1: |
| 49 | + years -= 1 |
| 50 | + months += 12 |
| 51 | + |
| 52 | + return self.__class__(years=years, |
| 53 | + months=months, |
| 54 | + days=self.days + other.days, |
| 55 | + hours=self.hours + other.hours, |
| 56 | + minutes=self.minutes + other.minutes, |
| 57 | + seconds=self.seconds + other.seconds, |
| 58 | + calendar=self.calendar) |
| 59 | + |
| 60 | + year = other.year+self.years |
| 61 | + |
| 62 | + month = other.month |
| 63 | + if self.months != 0: |
| 64 | + assert 1 <= abs(self.months) <= 12 |
| 65 | + month += self.months |
| 66 | + if month > 12: |
| 67 | + year += 1 |
| 68 | + month -= 12 |
| 69 | + elif month < 1: |
| 70 | + year -= 1 |
| 71 | + month += 12 |
| 72 | + |
| 73 | + if self.calendar == 'gregorian': |
| 74 | + daysInMonth = monthrange(year, month)[1] |
| 75 | + elif self.calendar == 'gregorian_noleap': |
| 76 | + # use year 0001, which is not a leapyear |
| 77 | + daysInMonth = monthrange(1, month)[1] |
| 78 | + |
| 79 | + day = min(daysInMonth, other.day) |
| 80 | + repl = {"year": year, "month": month, "day": day} |
| 81 | + |
| 82 | + days = self.days |
| 83 | + if self.calendar == 'gregorian_noleap' and isleap(year): |
| 84 | + if month == 2 and day+days >= 29: |
| 85 | + # skip forward over the leap day |
| 86 | + days += 1 |
| 87 | + elif month == 3 and day+days <= 0: |
| 88 | + # skip backward over the leap day |
| 89 | + days -= 1 |
| 90 | + |
| 91 | + return (other.replace(**repl) + |
| 92 | + datetime.timedelta(days=days, |
| 93 | + hours=self.hours, |
| 94 | + minutes=self.minutes, |
| 95 | + seconds=self.seconds)) |
| 96 | + |
| 97 | + def __radd__(self, other): |
| 98 | + return self.__add__(other) |
| 99 | + |
| 100 | + def __rsub__(self, other): |
| 101 | + return self.__neg__().__add__(other) |
| 102 | + |
| 103 | + def __sub__(self, other): |
| 104 | + if not isinstance(other, MpasRelativeDelta): |
| 105 | + return NotImplemented |
| 106 | + return self.__add__(other.__neg__()) |
| 107 | + |
| 108 | + def __neg__(self): |
| 109 | + return self.__class__(years=-self.years, |
| 110 | + months=-self.months, |
| 111 | + days=-self.days, |
| 112 | + hours=-self.hours, |
| 113 | + minutes=-self.minutes, |
| 114 | + seconds=-self.seconds, |
| 115 | + calendar=self.calendar) |
| 116 | + |
| 117 | + def __mul__(self, other): |
| 118 | + try: |
| 119 | + f = float(other) |
| 120 | + except TypeError: |
| 121 | + return NotImplemented |
| 122 | + |
| 123 | + return self.__class__(years=int(self.years * f), |
| 124 | + months=int(self.months * f), |
| 125 | + days=int(self.days * f), |
| 126 | + hours=int(self.hours * f), |
| 127 | + minutes=int(self.minutes * f), |
| 128 | + seconds=int(self.seconds * f), |
| 129 | + calendar=self.calendar) |
| 130 | + |
| 131 | + __rmul__ = __mul__ |
| 132 | + |
| 133 | + def __div__(self, other): |
| 134 | + try: |
| 135 | + reciprocal = 1 / float(other) |
| 136 | + except TypeError: |
| 137 | + return NotImplemented |
| 138 | + |
| 139 | + return self.__mul__(reciprocal) |
| 140 | + |
| 141 | + __truediv__ = __div__ |
| 142 | + |
| 143 | + def __repr__(self): |
| 144 | + l = [] |
| 145 | + for attr in ["years", "months", "days", "leapdays", |
| 146 | + "hours", "minutes", "seconds", "microseconds"]: |
| 147 | + value = getattr(self, attr) |
| 148 | + if value: |
| 149 | + l.append("{attr}={value:+g}".format(attr=attr, value=value)) |
| 150 | + l.append("calendar='{}'".format(self.calendar)) |
| 151 | + return "{classname}({attrs})".format(classname=self.__class__.__name__, |
| 152 | + attrs=", ".join(l)) |
| 153 | + |
| 154 | +# vim: foldmethod=marker ai ts=4 sts=4 et sw=4 ft=python |
0 commit comments