Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make cftime.datetime - cftime.datetime -> timedelta microsecond-exact #178

Merged
merged 4 commits into from
Jun 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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