Search code examples
pythonpandasdatetimefloating-pointtimedelta

Why does dividing by np.timedelta(...) provide a float answer from the difference between two datetime objects?


Say I have two datetime (or timestamp) variables and I am trying to get the difference between them. I can do:

diff = date1 - date2

This results in a timedelta object (or an array of dtype=timedelta64, if you were using two series of datetimes).

Then, if I want the float value of diff in number of days, I can perform:

diff / np.timedelta64(24, 'h') # np.timedelta64(1, 'd') works the same, IIRC.

This results in a float value, as stated, which you can then use arithmetic comparisons on.

What I don't understand from the documentation or google searching is why this works as a mathematical operation, when it feels much more like I'm simply converting from timedelta to float, and then selecting only the day value.

I'm most likely just not understanding the specifics of timedelta, but I'm hoping someone else understands it much better than I do, and can explain the logic behind this.


Solution

  • From my understanding of the general logic behind all of time issues the timedelta64 is just a 64 bit number representing a span of time. This span can be expressed in hours or days, but not in months or years because the number of months or years depends on the "position" of the span on a time-line.

    Hours or days can be calculated from the number representing time difference by dividing it by the amount of "units" an hour or day is represented in, so division is the right way of obtaining the appropriate result from the timedelta64 values.

    numpy documentation states on timedelta:

    NumPy allows the subtraction of two datetime values, an operation which produces a number with a time unit.

    I am following from this that the timedelta is just a number which value/order is defined by the associated unit, so it can be then converted to another units in a way units are converted from one to another and this is usually done by multiplication, division, addition and subtraction - which all are arithmetic operations on numbers.