0

This is my code:

import datetime, time 
def function():
    start = datetime.now()
    ...
    stop = datetime.now()
    result = (stop - start).total_seconds()
    return result

But when I execute it, it returns 0... why tho

tjardskleener
  • 33
  • 1
  • 5

3 Answers3

0

As is, the code does not run at all and not return anything. Instead, I get an Attribute error:

AttributeError: module 'datetime' has no attribute 'now'

When I fix your code (from datetime import datetime) and run it, the result is

0:00:00

which is likely hours, minutes and seconds. That is with ... as the only command between start and stop. If the ... part takes muss less than a millisecond, it may not be detected. I doubt that it takes 50 ms as stated by you in a comment (see also below).

Can I call the current time two times in one function?

Yes:

import time
from datetime import datetime
def function():
    start = datetime.now()
    time.sleep(.001)
    stop = datetime.now()
    result = stop - start
    return result

print(function())

0:00:00.001994

As you see, at 1 ms sleep time, the measured time is off by ~100% and times are not accurate any more.

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
0

If you don't need the date, you could just run the following:

import time

def function():
    start_time = time.time()
    time.sleep(5)
    end_time = time.time()
    print(f'Completed in: {end_time - start_time} seconds')

function()
Sam
  • 533
  • 3
  • 12
0

it does the right thing for me under Linux (5.3), i.e:

from datetime import datetime
(datetime.now() - datetime.now()).total_seconds()

evaluates to -8e-06 which is good. I'd therefore assume the timer used under your Windows system isn't very high precision. I'd suggest using time.perf_counter() for these sorts of short durations, datetime is more for when you care about obscure human things like months.

for example

from time import perf_counter

perf_counter() - perf_counter()

gives me approx -2.8e-7, so we've also reduced the duration of the call to a few hundred nanoseconds.

chepner
  • 497,756
  • 71
  • 530
  • 681
Sam Mason
  • 15,216
  • 1
  • 41
  • 60
  • @chepner I'm aware of that, I was the one that initially made a comment suggesting it could be platform specific! the above was to demonstrate that the code can work and that alternatives exist for measuring small time intervals – Sam Mason Oct 29 '19 at 13:09