Skip to content

Commit

Permalink
Merge pull request #178 from spencerkclark/exact-date2num
Browse files Browse the repository at this point in the history
Make cftime.datetime - cftime.datetime -> timedelta microsecond-exact
  • Loading branch information
jswhit authored Jun 23, 2020
2 parents 76e2b10 + b795635 commit fa1d226
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
10 changes: 8 additions & 2 deletions cftime/_cftime.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1793,8 +1793,14 @@ Gregorial calendar.
raise ValueError("cannot compute the time difference between dates with different calendars")
if dt.calendar == "":
raise ValueError("cannot compute the time difference between dates that are not calendar-aware")
converter = _converters[dt.calendar]
return timedelta(seconds=converter.date2num(dt) - converter.date2num(other))
ordinal_self = _IntJulianDayFromDate(dt.year, dt.month, dt.day, dt.calendar)
ordinal_other = _IntJulianDayFromDate(other.year, other.month, other.day, other.calendar)
days = ordinal_self - ordinal_other
seconds_self = dt.second + 60 * dt.minute + 3600 * dt.hour
seconds_other = other.second + 60 * other.minute + 3600 * other.hour
seconds = seconds_self - seconds_other
microseconds = dt.microsecond - other.microsecond
return timedelta(days, seconds, microseconds)
elif isinstance(other, datetime_python):
# datetime - real_datetime
if not dt.datetime_compatible:
Expand Down
8 changes: 8 additions & 0 deletions test/test_cftime.py
Original file line number Diff line number Diff line change
Expand Up @@ -1583,6 +1583,14 @@ def test_dayofyr_after_timedelta_addition(date_type):
assert date_after_timedelta_addition.dayofyr == 3


def test_exact_datetime_difference(date_type):
b = date_type(2000, 1, 2, 0, 0, 0, 5)
a = date_type(2000, 1, 2)
result = b - a
expected = timedelta(microseconds=5)
assert result == expected


_SHAPES = [(4, ), (2, 2)]
_MICROSECOND_UNITS = ["microseconds", "microsecond", "microsec", "microsecs"]
_MILLISECOND_UNITS = ["milliseconds", "millisecond", "millisec", "millisecs", "ms"]
Expand Down

0 comments on commit fa1d226

Please sign in to comment.