Skip to content

'second' is an invalid keyward argument for replace() when using truncate_datetime and a date object #564

@SecretUnicorn

Description

@SecretUnicorn

When using truncate_datetime in combination with datetime objects everything works correctly:

>>> d1 = {'a': datetime.datetime(2020, 5, 17)}
>>> d2 = {'a': datetime.datetime(2020, 5, 17)}
>>> DeepDiff(d1, d2, truncate_datetime='minute')

Using datetime.dates results in the following error:

>>> d1 = {'a': datetime.date(2020, 5, 17)}
>>> d2 = {'a': datetime.date(2020, 5, 17)}
>>> DeepDiff(d1, d2, truncate_datetime='minute')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/django/apps/bautool/venv/lib/python3.10/site-packages/deepdiff/diff.py", line 361, in __init__
    self._diff(root, parents_ids=frozenset({id(t1)}), _original_type=_original_type)
  File "/opt/django/apps/bautool/venv/lib/python3.10/site-packages/deepdiff/diff.py", line 1725, in _diff
    self._diff_dict(level, parents_ids, local_tree=local_tree)
  File "/opt/django/apps/bautool/venv/lib/python3.10/site-packages/deepdiff/diff.py", line 706, in _diff_dict
    self._diff(next_level, parents_ids_added, local_tree=local_tree)
  File "/opt/django/apps/bautool/venv/lib/python3.10/site-packages/deepdiff/diff.py", line 1716, in _diff
    self._diff_time(level, local_tree=local_tree)
  File "/opt/django/apps/bautool/venv/lib/python3.10/site-packages/deepdiff/diff.py", line 1529, in _diff_time
    level.t1 = datetime_normalize(self.truncate_datetime, level.t1, default_timezone=self.default_timezone)
  File "/opt/django/apps/bautool/venv/lib/python3.10/site-packages/deepdiff/helper.py", line 631, in datetime_normalize
    obj = obj.replace(second=0, microsecond=0)
TypeError: 'second' is an invalid keyword argument for replace()

I checked the source code and it happens because of these lines:

deepdiff/deepdiff/diff.py

Lines 1769 to 1770 in b639fec

elif isinstance(level.t1, (datetime.date, datetime.timedelta, datetime.time)):
self._diff_time(level, local_tree=local_tree)

A date object has no time component so a truncation should not be necessary. Comparing two dates via the times is probably also wrong. Maybe adding another elif clause and a _diff_date function does the trick?

I will post a merge request if I find the time. Otherwise I would be happy with a quick fix.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions