Convert timedelta to floating-point

隐身守侯 提交于 2019-11-27 11:28:10

问题


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.


回答1:


You could use the total_seconds method:

time_d_float = time_d.total_seconds()



回答2:


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)



回答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!




回答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)



回答5:


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()                  


来源:https://stackoverflow.com/questions/21414639/convert-timedelta-to-floating-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!