time1 = datetime.now();
time1 -= time1;
time2 = datetime.now();
time2 -= time2;
这就是我如何尝试将日期时间定义为等于零。 什么是正确的方法?
这就是我想要做的事情:
import urllib2
from datetime import datetime
time1 = datetime.now();
time1 -= time1;
time2 = datetime.now();
time2 -= time2;
for i in range(0, 5):
x = datetime.now()
response = urllib2.urlopen("http://www.google.com")
time1 += datetime.now() - x
x = datetime.now()
response = urllib2.urlopen("http://facebook.com")
time2 += datetime.now() - x
print time1
print time2
它有效,但我认为这样做是错误的。
答案 0 :(得分:2)
正如文件所述,施工方法如下:
datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
datetime.MINYEAR
为1
,这意味着最低年份值为1
。因此,您无法将datetime
定义为等于Zero
。用你的方法:
time1 = datetime.now();
time1 -= time1;
对象time1
已更改为datetime.timedelta
而非datetime.datetime
对象。
>>> time1 = datetime.datetime.now();
>>> time1
datetime.datetime(2013, 6, 9, 11, 13, 3, 57000)
>>> type(time1)
<class 'datetime.datetime'>
>>> time1 -= time1;
>>> time1
datetime.timedelta(0)
>>> type(time1)
<class 'datetime.timedelta'>
感谢@falsetru,将timedelta定义为零的方法,我们应该这样做:
zero = timedelta(0)
答案 1 :(得分:0)
from datetime import datetime, timedelta
import urllib2
def benchmark(url, count=5):
elapsed = timedelta(0)
for i in range(count):
time1 = datetime.now()
u = urllib2.urlopen(url)
try:
u.read()
finally:
u.close()
time2 = datetime.now()
elapsed += time2 - time1
return elapsed
for url in ("http://www.google.com", "http://facebook.com"):
print url
print benchmark(url)