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?
With true division,
1 / 2would result in0.5. The default behavior in Python 2.x is to use integer division, where1 / 2would result in0. Here is the explanation from the docs:To enable true division on Python 2.2 or higher (not necessary on Python 3.x), you can use the following:
Alternatively, you can just make one of the arguments a float to get the same behavior: