How Can I Convert datetime.timedelta to int?
Question:
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
?
Answers:
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
For the above question, OP can use this print
statement for timedelta as a number in µs.
print(
'Random Forest Time Duration (in µs) -',
rf_time / datetime.timedelta(microseconds=1)
)
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
?
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
For the above question, OP can use this print
statement for timedelta as a number in µs.
print(
'Random Forest Time Duration (in µs) -',
rf_time / datetime.timedelta(microseconds=1)
)