Python 将 timedelta 转换为浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21414639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert timedelta to floating-point
提问by fidelitas
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.
我从两个日期时间的减法中得到了一个 timedelta 对象。我需要这个值作为进一步计算的浮点数。我发现的所有内容都可以使用浮点进行计算,但结果仍然是 timedelta 对象。
time_d = datetime_1 - datetime_2
time_d_float = float(time_d)
does not work.
不起作用。
采纳答案by unutbu
回答by dan04
In Python 3.2or 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.
在 Python 3.2或更高版本中,您可以将两个timedeltas 相除以给出一个浮点数。如果您需要该值的单位不是秒,这将很有用。
time_d_min = time_d / datetime.timedelta(minutes=1)
time_d_ms = time_d / datetime.timedelta(milliseconds=1)
回答by Faith
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.
我之前遇到过同样的问题,我使用 timedelta.total_seconds 将估计持续时间转换为浮点数,并且它有效。我希望这对你有用。
from datetime import timedelta,datetime
time_d = datetime_1 - datetime_2
time_d.total_seconds()
回答by RoachLord
If you needed the number of days as a floating number you can use timedelta's days attribute
如果您需要天数作为浮点数,您可以使用 timedelta 的 days 属性
time_d = datetime_1 - datetime_2
number_of_days = float(time_d.days)
回答by Monique Marins
You could use numpyto solve that:
你可以使用numpy来解决这个问题:
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!
希望它有帮助!

