简体   繁体   English

将timedelta转换为浮点数

[英]Convert timedelta to floating-point

I got a timedelta object from the subtraction of two datetimes. 我从减去两个日期时间得到了一个timedelta对象。 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对象。

time_d = datetime_1 - datetime_2
time_d_float = float(time_d)

does not work. 不起作用。

您可以使用total_seconds方法:

time_d_float = time_d.total_seconds()

In recent versions of Python, you can divide two timedelta s to give a float. 在Python的最新版本中,您可以将两个timedelta划分为一个浮点数。 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)

You could use numpy to 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! 希望它有用!

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)

I had the same problem before and I used timedelta.total_seconds to get Estimated duration into seconds with float and it works. 之前我遇到了同样的问题,我使用timedelta.total_seconds将估计的持续时间变为秒,并使用浮点数并且它可以工作。 I hope this works for you. 我希望这适合你。

from datetime import timedelta,datetime

time_d = datetime_1 - datetime_2

time_d.total_seconds()                  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM