0
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

它有效,但我认为这样做是错误的。

4

2 回答 2

3

如文件所述,构造方法如下:

datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])

datetime.MINYEARis 1,表示最小年份值为1。所以你不能定义 adatetime等于Zero。用你的方法:

 time1 = datetime.now();
 time1 -= time1;

对象time1变为datetime.timedeltadatetime.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,将时间增量定义为零的方法,我们应该这样做:

zero = timedelta(0) 
于 2013-06-09T16:07:54.480 回答
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)
于 2013-06-09T16:24:11.710 回答