Convert timedelta to floating-point
81,897
Solution 1
You could use the total_seconds
method:
time_d_float = time_d.total_seconds()
Solution 2
In Python 3.2 or higher, you can divide two timedelta
s 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
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
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)
Author by
fidelitas
Updated on July 05, 2022Comments
-
fidelitas almost 2 years
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.
-
umbreonben over 9 yearsI get AttributeError: 'datetime.timedelta' object has no attribute 'total_seconds'.
-
Will Hardy over 9 years
timedelta.total_seconds()
was introduced in Python 2.7/3.2 -
Ironcache almost 8 yearsHow does this add anything over the currently-accepted answer?
-
lancew over 6 yearsI get this error with your suggestion: AttributeError: 'datetime.timedelta' object has no attribute 'apply'
-
Monique Marins over 6 yearsHi @lancew, thanks for catching that! In that case, I needed to convert a dataframe to float so it worked out for me. If you want to convert a unique value, you could do it:
pd.DataFrame([time_d]).apply(np.float32)
. In this case, you need to import both 'pandas as pd' and 'numpy as np'. Although I'll be testing other ways. Please, let me know if it works. -
Wolf over 4 yearsI see this as the most natural way to do it. Besides that, it's also great for adapting time implementations of other languages/systems.
-
Mache over 3 years@aaa90210 - it's a method and should be used with ()
-
Skippy le Grand Gourou over 3 yearsNot to be confused with
timedelta.seconds
(which returns an int, BTW). -
supercooler8 about 3 yearsNow, I get this error: "TypeError: float() argument must be a string or a number, not 'Timedelta'"
-
lpnorm almost 3 yearsThis gives the number of days only. You lose whatever amount of hours minutes or seconds you have in time_d. This is not accurate.
-
Just_Alex about 2 yearsI had a similar issue. I solved it using
to_numpy()
e.g.df["column"].to_numpy().astype(float)
. Also see solution here stackoverflow.com/questions/49370756/…. -
Joe Sadoski almost 2 years@SkippyleGrandGourou furthermore, it doesn't round up for you - it's the literal seconds value without the milliseconds.