python求时间差

转自:http://blog.sina.com.cn/s/blog_519ccabf01010ykx.html

1.python求时间差不能使用time()模块,eg:
t1 = time.ctime()
time.sleep(3)
t2 = time.ctime()
t = t2 - t1    ###会报错,不能相减

2.需要使用datetime模块,datetime模块比time模块更能更强。
d1 = datetime.datetime.now()
time.sleep(3)
d2 = datetime.datetime.now()
d = d2-d1      ### 产生的是 datetime.timedelta 对象

d.days 天
d.max 最大
d.microseconds 微秒
d.min 最小
d.resolution
d.seconds 秒

注: d1, d2 还可以格式化成正常的日期时间。
e.g:
t_now = str(d1)  ### t_now = '2012-02-17 12:49:04.828000'  精确到毫秒
t_now[:19]  ## 秒级别 '2012-02-17 12:49:04'
t_now[:10]  ## 日期级别 '2012-02-17'

可根据需要自己裁定


测试模块:

测试报告:


logs = Log.objects.order_by('-start_time')
    d1 =  datetime.datetime.now()
    #logs = logs.order_by('start_time')
    log_list = list(logs)
    log_list.sort(key=operator.attrgetter('start_time'), reverse=False)
    d2 =  datetime.datetime.now()
    d =  d2 - d1
    print d


0:00:00.811000
[12/Nov/2012 18:06:24] "GET /log/index/?_=1352714783865 HTTP/1.1" 200 10564
0:00:00.780000
[12/Nov/2012 18:06:43] "GET /log/index/?_=1352714802185 HTTP/1.1" 200 10564
0:00:00.764000
[12/Nov/2012 18:07:06] "GET /log/index/?_=1352714825224 HTTP/1.1" 200 10564
0:00:00.749000
[12/Nov/2012 18:07:07] "GET /log/index/?_=1352714827160 HTTP/1.1" 200 10564
0:00:00.780000
[12/Nov/2012 18:07:09] "GET /log/index/?_=1352714828683 HTTP/1.1" 200 10564






logs = Log.objects.order_by('-start_time')
    d1 =  datetime.datetime.now()
    #logs = logs.order_by('start_time')
    log_list = list(logs)
    log_list.sort(key=operator.attrgetter('start_time'), reverse=True)
    d2 =  datetime.datetime.now()
    d =  d2 - d1
    print d


0:00:00.780000
[12/Nov/2012 18:09:12] "GET /log/index/?_=1352714951344 HTTP/1.1" 200 10564
0:00:00.780000
[12/Nov/2012 18:09:48] "GET /log/index/?_=1352714987642 HTTP/1.1" 200 10564
0:00:00.764000
[12/Nov/2012 18:09:50] "GET /log/index/?_=1352714989233 HTTP/1.1" 200 10564
0:00:00.780000
[12/Nov/2012 18:09:51] "GET /log/index/?_=1352714990809 HTTP/1.1" 200 10564
0:00:00.795000
[12/Nov/2012 18:09:53] "GET /log/index/?_=1352714992482 HTTP/1.1" 200 10564
0:00:00.796000
[12/Nov/2012 18:09:55] "GET /log/index/?_=1352714994265 HTTP/1.1" 200 10564






logs = Log.objects.order_by('-start_time')
    d1 =  datetime.datetime.now()
    logs = logs.order_by('start_time')
    #log_list = list(logs)[0:10]
    #log_list.sort(key=operator.attrgetter('start_time'), reverse=False)
    d2 =  datetime.datetime.now()
    d =  d2 - d1
    print d




0:00:00
[12/Nov/2012 18:18:14] "GET /log/index/?_=1352715494293 HTTP/1.1" 200 10667
0:00:00
[12/Nov/2012 18:18:15] "GET /log/index/?_=1352715494940 HTTP/1.1" 200 10667
0:00:00
[12/Nov/2012 18:18:15] "GET /log/index/?_=1352715495661 HTTP/1.1" 200 10667
0:00:00
[12/Nov/2012 18:18:16] "GET /log/index/?_=1352715496335 HTTP/1.1" 200 10667
0:00:00
[12/Nov/2012 18:18:17] "GET /log/index/?_=1352715497517 HTTP/1.1" 200 10667







你可能感兴趣的:(Python)