Calculating Time Difference

2019-01-17 02:50发布

at the start and end of my program, I have

from time import strftime
print int(strftime("%Y-%m-%d %H:%M:%S")



Y1=int(strftime("%Y"))
m1=int(strftime("%m"))
d1=int(strftime("%d"))
H1=int(strftime("%H"))
M1=int(strftime("%M"))
S1=int(strftime("%S"))


Y2=int(strftime("%Y"))
m2=int(strftime("%m"))
d2=int(strftime("%d"))
H2=int(strftime("%H"))
M2=int(strftime("%M"))
S2=int(strftime("%S"))

print "Difference is:"+str(Y2-Y1)+":"+str(m2-m1)+":"+str(d2-d1)\
          +" "+str(H2-H1)+":"+str(M2-M1)+":"+str(S2-S1)

But when I tried to get the difference, I get syntax errors.... I am doing a few things wrong, but I'm not sure what is going on...

Basically, I just want to store a time in a variable at the start of my program, then store a 2nd time in a second variable near the end, then at the last bit of the program, compute the difference and display it. I am not trying to time a function speed. I am trying to log how long it took for a user to progress through some menus. What is the best way to do this?

标签: python time
4条回答
在下西门庆
2楼-- · 2019-01-17 03:31
from time import time
start_time = time()

...

end_time = time()
time_taken = end_time - start_time # time_taken is in seconds

hours, rest = divmod(time_taken,3600)
minutes, seconds = divmod(rest, 60)

# starttime changed to start_time

查看更多
贼婆χ
3楼-- · 2019-01-17 03:33

The datetime module will do all the work for you:

>>> import datetime
>>> a = datetime.datetime.now()
>>> # ...wait a while...
>>> b = datetime.datetime.now()
>>> print(b-a)
0:03:43.984000

If you don't want to display the microseconds, just use (as gnibbler suggested):

>>> a = datetime.datetime.now().replace(microsecond=0)
>>> b = datetime.datetime.now().replace(microsecond=0)
>>> print(b-a)
0:03:43
查看更多
聊天终结者
4楼-- · 2019-01-17 03:41

time.monotonic() (basically your computer's uptime in seconds) is guarranteed to not misbehave when your computer's clock is adjusted (such as when transitioning to/from daylight saving time).

>>> import time
>>>
>>> time.monotonic()
452782.067158593
>>>
>>> a = time.monotonic()
>>> time.sleep(1)
>>> b = time.monotonic()
>>> print(b-a)
1.001658110995777
查看更多
甜甜的少女心
5楼-- · 2019-01-17 03:42

You cannot calculate the differences separately ... what difference would that yield for 7:59 and 8:00 o'clock? Try

import time
time.time()

which gives you the seconds since the start of the epoch.

You can then get the intermediate time with something like

timestamp1 = time.time()
# Your code here
timestamp2 = time.time()
print "This took %.2f seconds" % (timestamp2 - timestamp1)
查看更多
登录 后发表回答