Convert timedelta to floating-point

PythonDatetimePython 2.7Floating PointTimedelta

Python Problem Overview


I got a timedelta object from the subtraction of two datetimes. I need this value as floating point for further calculations. All that I've found enables the calculation with floating-points, but the result is still a timedelta object.

time_d = datetime_1 - datetime_2
time_d_float = float(time_d)

does not work.

Python Solutions


Solution 1 - Python

You could use the total_seconds method:

time_d_float = time_d.total_seconds()

Solution 2 - Python

In Python 3.2 or higher, you can divide two timedeltas to give a float. This is useful if you need the value to be in units other than seconds.

time_d_min = time_d / datetime.timedelta(minutes=1)
time_d_ms  = time_d / datetime.timedelta(milliseconds=1)

Solution 3 - Python

You could use numpy to solve that:

import pandas as pd
import numpy as np

time_d = datetime_1 - datetime_2

#for a single value
number_of_days =pd.DataFrame([time_d]).apply(np.float32)
 
#for a Dataframe
number_of_days = time_d.apply(np.float32)

Hope it is helpful!

Solution 4 - Python

If you needed the number of days as a floating number you can use timedelta's days attribute

time_d = datetime_1 - datetime_2
number_of_days = float(time_d.days)

Solution 5 - Python

from datetime import timedelta,datetime
x1= timedelta(seconds=40, minutes=40, hours=5)
x2= timedelta( seconds=50, minutes=20, hours=4)
x3=x1-x2
x5 = x3.total_seconds()
print(x5)
print(type(x5))
print(type(x1))
print(x1)

# if you are working with Dataframe then use loop (* for-loop).

Solution 6 - Python

I had the same problem before and I used timedelta.total_seconds to get Estimated duration into seconds with float and it works. I hope this works for you.

from datetime import timedelta,datetime

time_d = datetime_1 - datetime_2

time_d.total_seconds()                  

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfidelitasView Question on Stackoverflow
Solution 1 - PythonunutbuView Answer on Stackoverflow
Solution 2 - Pythondan04View Answer on Stackoverflow
Solution 3 - PythonMonique MarinsView Answer on Stackoverflow
Solution 4 - PythonRoachLordView Answer on Stackoverflow
Solution 5 - PythonMrityunjaya ChauhanView Answer on Stackoverflow
Solution 6 - PythonFaithView Answer on Stackoverflow