Home > Net >  How Can I Convert datetime.timedelta to int?
How Can I Convert datetime.timedelta to int?

Time:08-19

I wrote these codes for prediction and test accuracy on some dataset with the help of sklearn random forest classifier.

Code

a = datetime.datetime.now()
y_pred=clf.predict(X_test)
b = datetime.datetime.now()

rf_time = b-a

rf_ac = metrics.accuracy_score(y_test, y_pred)

print(type(rf_time))
print('Random Forest Time Duration - ',b-a)
print("Random Forest Accuracy:",metrics.accuracy_score(y_test, y_pred))

Output

<class 'datetime.timedelta'>
Random Forest Time Duration -  0:00:00.011969
Random Forest Accuracy: 0.6324761904761905

Here I got the rf_time which type is datetime.timedelta. Now, How can I convert this datetime.timedelta into integer. How can I get the int value from the 0:00:00.011969?

CodePudding user response:

it depends on what unit you want you interger to be: for seconds you could use:

from datetime import timedelta
rf_time = timedelta(hours=1)
t_integer = int(t.total_seconds())
t_integer

output:
enter image description here

enter image description here

if you want ns you can use:

t_integer = int(t.total_seconds() * 1e9)

output:
enter image description here

for us you can use * 1e6 etc

CodePudding user response:

The generic form to get timedelta in UNIT is:

delta / timedelta(UNIT=1)

with UNIT one of days, hours, minutes, seconds, microseconds, milliseconds.

NB. this is a division, which in python always gives a float, so you might need to convert/display as int manually.

For seconds, there is timedelta.total_seconds().

Example:

timedelta(days=1) / timedelta(hours=1)  # gives 24.0
  • Related