MCPcopy Index your code
hub / github.com/python-pendulum/pendulum / precise_diff

Function precise_diff

src/pendulum/_helpers.py:161–306  ·  view source on GitHub ↗

Calculate a precise difference between two datetimes. :param d1: The first datetime :param d2: The second datetime

(
    d1: datetime.datetime | datetime.date, d2: datetime.datetime | datetime.date
)

Source from the content-addressed store, hash-verified

159
160
161def precise_diff(
162 d1: datetime.datetime | datetime.date, d2: datetime.datetime | datetime.date
163) -> PreciseDiff:
164 """
165 Calculate a precise difference between two datetimes.
166
167 :param d1: The first datetime
168 :param d2: The second datetime
169 """
170 sign = 1
171
172 if d1 == d2:
173 return PreciseDiff(0, 0, 0, 0, 0, 0, 0, 0)
174
175 tzinfo1: datetime.tzinfo | None = (
176 d1.tzinfo if isinstance(d1, datetime.datetime) else None
177 )
178 tzinfo2: datetime.tzinfo | None = (
179 d2.tzinfo if isinstance(d2, datetime.datetime) else None
180 )
181
182 if (tzinfo1 is None and tzinfo2 is not None) or (
183 tzinfo2 is None and tzinfo1 is not None
184 ):
185 raise ValueError(
186 "Comparison between naive and aware datetimes is not supported"
187 )
188
189 if d1 > d2:
190 d1, d2 = d2, d1
191 sign = -1
192
193 d_diff = 0
194 hour_diff = 0
195 min_diff = 0
196 sec_diff = 0
197 mic_diff = 0
198 total_days = _day_number(d2.year, d2.month, d2.day) - _day_number(
199 d1.year, d1.month, d1.day
200 )
201 in_same_tz = False
202 tz1 = None
203 tz2 = None
204
205 # Trying to figure out the timezone names
206 # If we can't find them, we assume different timezones
207 if tzinfo1 and tzinfo2:
208 tz1 = _get_tzinfo_name(tzinfo1)
209 tz2 = _get_tzinfo_name(tzinfo2)
210
211 in_same_tz = tz1 == tz2 and tz1 is not None
212
213 if isinstance(d2, datetime.datetime):
214 if isinstance(d1, datetime.datetime):
215 # If we are not in the same timezone
216 # we need to adjust
217 #
218 # We also need to adjust if we do not

Callers 3

__init__Method · 0.90
test_precise_diffFunction · 0.90

Calls 5

PreciseDiffClass · 0.85
_day_numberFunction · 0.85
_get_tzinfo_nameFunction · 0.85
is_leapFunction · 0.85
utcoffsetMethod · 0.80

Tested by 2

test_precise_diffFunction · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…