Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computing total_seconds in Python for datetime module with true division enabled

I'm trying to do some computations on date, I have a timedelta object, and I want to get the number of seconds. It seems like dt.total_seconds() does exactly what I need but unfortunately it was introduced in Python 2.7 and I'm stuck with an older version.

If I read the official documentation, it states the following:

Return the total number of seconds contained in the duration. Equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 computed with true division enabled.

And after looking at the source of the datetime module (in C), I see something like this:

total_seconds = PyNumber_TrueDivide(total_microseconds, one_million);

So while the computation of total_seconds() seems trivial, that leaves me wondering what this true division actually means. I couldn't find any info on the topic. What happens if I just use regular division, why do we need this true division and what does it do? Can I just write total_seconds() in Python with the equivalent given in the doc?

like image 257
Charles Menguy Avatar asked Apr 26 '12 18:04

Charles Menguy


1 Answers

With true division, 1 / 2 would result in 0.5. The default behavior in Python 2.x is to use integer division, where 1 / 2 would result in 0. Here is the explanation from the docs:

Plain or long integer division yields an integer of the same type; the result is that of mathematical division with the ‘floor’ function applied to the result.

To enable true division on Python 2.2 or higher (not necessary on Python 3.x), you can use the following:

from __future__ import division

Alternatively, you can just make one of the arguments a float to get the same behavior:

(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10.0**6
like image 157
Andrew Clark Avatar answered Oct 24 '22 08:10

Andrew Clark