计算时差

在我的节目的开始和结束,我有

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)

但是当我试图得到差异时,我得到了语法错误... ..。我确实做错了一些事,但我不知道发生了什么..。

基本上,我只想在程序开始的时候,在一个变量中存储一个时间,然后在接近结束的时候,在第二个变量中存储第二个时间,然后在程序的最后一个位,计算差值并显示出来。我不是在计算函数速度。我试图记录用户通过一些菜单进行操作所花费的时间。最好的方法是什么?

201528 次浏览
from time import time


start_time = time()
...


end_time = time()
seconds_elapsed = end_time - start_time


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

你不能分开计算差异... 7:59和8:00会有什么差异? 试试看

import time
time.time()

也就是新纪元开始后的秒数。

然后你可以得到中间时间

timestamp1 = time.time()
# Your code here
timestamp2 = time.time()
print "This took %.2f seconds" % (timestamp2 - timestamp1)

datetime模块将为您完成所有工作:

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

如果您不想显示微秒,只需使用(正如 nibbler 建议的那样) :

>>> a = datetime.datetime.now().replace(microsecond=0)
>>> b = datetime.datetime.now().replace(microsecond=0)
>>> print(b-a)
0:03:43

时间,单调单调 _ ns ()都是正确的,就像单调一样正确。

>>> import time
>>>
>>> time.monotonic()
452782.067158593
>>>
>>> t0 = time.monotonic()
>>> time.sleep(1)
>>> t1 = time.monotonic()
>>> print(t1 - t0)
1.001658110995777

不管语言如何,单调的时间是正确的答案,而 真正的时间是错误的答案。区别在于,单调时间理应在测量持续时间时给出一致的答案,而实际时间则不是,因为实际时间可能会被调整——实际上是 需求被调整——以跟上现实。单调时间通常是计算机的正常运行时间。

因此,时间,时间Datetime.now ()这样做是错误的。

Python 还有 Perf _ counter ()Perf _ counter _ ns (),它们被指定为具有最高的可用分辨率,但不保证是单调的。不过,在 PC 硬件上,两者通常都具有纳秒级的分辨率。

下面是这样做的一段代码:

Def (StringChallenge (str1)) :

#str1 = str1[1:-1]
h1 = 0
h2 = 0
m1 = 0
m2 = 0


def time_dif(h1,m1,h2,m2):
if(h1 == h2):
return m2-m1
else:
return ((h2-h1-1)*60 + (60-m1) + m2)
count_min = 0


if str1[1] == ':':
h1=int(str1[:1])
m1=int(str1[2:4])
else:
h1=int(str1[:2])
m1=int(str1[3:5])


if str1[-7] == '-':
h2=int(str1[-6])
m2=int(str1[-4:-2])
else:
h2=int(str1[-7:-5])
m2=int(str1[-4:-2])


if h1 == 12:
h1 = 0
if h2 == 12:
h2 = 0


if "am" in str1[:8]:
flag1 = 0
else:
flag1= 1


if "am" in str1[7:]:
flag2 = 0
else:
flag2 = 1


if flag1 == flag2:
if h2 > h1 or (h2 == h1 and m2 >= m1):
count_min += time_dif(h1,m1,h2,m2)
else:
count_min += 1440 - time_dif(h2,m2,h1,m1)
else:
count_min += (12-h1-1)*60
count_min += (60 - m1)
count_min += (h2*60)+m2




return count_min