4

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'
Community
  • 1
  • 1
Romaldowoho
  • 405
  • 1
  • 7
  • 20

3 Answers3

4

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()
isedev
  • 18,848
  • 3
  • 60
  • 59
1

Use datetime.timedelta.total_seconds() to get seconds.

>>> start_time = datetime.now()
>>> t = datetime.now() - start_time
>>> t.total_seconds()
4.303854
falsetru
  • 357,413
  • 63
  • 732
  • 636
0

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
Alexander
  • 105,104
  • 32
  • 201
  • 196