Reputation: 415
This is my first experience with Python. I am trying to determine how long it take for my code to run. Here is what I have:
from datetime import datetime, timedelta
startTime = datetime.now()
#Some code
t = datetime.now() - startTime
print t.strftime("%S.%f")
But it gives me this error:
'datetime.timedelta' object has no attribute 'strftime'
What should I do? I found this example on StackOverflow that is supposed to work and followed it:
from datetime import datetime
now = datetime.now()
now.strftime("%H:%M:%S.%f")
>>'12:19:40.948000'
Upvotes: 4
Views: 819
Reputation: 109656
If you are using ipython or the Jupyter notebook, there is a built in magic function %time
to do such timing:
from time import sleep
%%time
sleep(1)
CPU times: user 336 µs, sys: 520 µs, total: 856 µs
Wall time: 1 s
Upvotes: 0
Reputation: 19641
datetime.now()
returns a datetime.datetime
object (which has a strftime
method).
However, when you subtract two such objects, you get a datetime.deltatime
object (which does not have a strftime
method).
You could achieve the result you are looking for like this:
print t.total_seconds()
Upvotes: 4
Reputation: 369314
Use datetime.timedelta.total_seconds()
to get seconds.
>>> start_time = datetime.now()
>>> t = datetime.now() - start_time
>>> t.total_seconds()
4.303854
Upvotes: 1