Skip to content

compare datetime objects with pytest.approx #4736

@brianmaissy

Description

@brianmaissy

I frequently find myself comparing datetime objects with an interval, and thought it would be convenient if approx() supported datetimes.

It would work similarly to numbers, except the absolute tolerance would be a timedelta, and the relative tolerance would be a number which would be interpreted as a fraction of the datetime's distance from the epoch, or something like that. Admittedly a relative tolerance has less of a use for datetimes, so I would make the default 0, and possibly even disable relative tolerances.

It doesn't solve a really critical problem, because subtracting datetimes and comparing against a timedelta isn't the end of the world, nor is converting them both to timestamps and comparing them as numbers with approx(), but I think it would be convenient.

While we are at it, we could also support comparing timedeltas themselves, which is even more straightforward.

I am a little concerned about the slippery slope of trying to support approximate comparison of every type, in which inevitably the semantics of approx() will break down, but in this case datetimes and timedeltas are pretty "number-like", in that they have a clear numerical interpretation, and already support arithmetic operations, absolute value, etc.

I considered implementing it as a plugin, but I think part of the convenience would be that the same approx() function which people already know and love would just work for datetimes.

Let me know if you think this is a good idea, and if so, I'd be happy to implement it.

Metadata

Metadata

Assignees

Labels

topic: approxrelated to pytest.approx functiontype: proposalproposal for a new feature, often to gather opinions or design the API around the new feature

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions