详解Python编程中time模块的使用
一、简介 time模块提供各种操作时间的函数
夏令时介绍:http://baike.baidu.com/view/100246.htm UTC介绍:http://wenda.tianya.cn/wenda/thread?tid=283921a9da7c5aef&clk=wttpcts 二、函数介绍 1.asctime() asctime([tuple]) -> string 将一个struct_time(默认为当时时间),转换成字符串 2.clock() clock() -> floating point number 注: 3.sleep(…) sleep(seconds) import time if __name__ == '__main__': time.sleep(3) print "clock1: %s" % time.clock() # print "local time: %s" % time.localtime() print str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())) time.sleep(3) print "clock2: %s" % time.clock() # print "local time: %s" % time.localtime() print str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())) time.sleep(3) print "clock3: %s" % time.clock() # print "local time: %s" % time.localtime() print str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())) 结果 clock1: 0.020678 2015-08-09 00:18:31 clock2: 0.020891 2015-08-09 00:18:34 clock3: 0.021068 2015-08-09 00:18:37 4.ctime(…) ctime(seconds) -> string time.ctime() 输出为: 'Sat Mar 28 22:24:24 2009′ 5.gmtime(…) gmtime([seconds]) -> (tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst) 6.localtime(…) localtime([seconds]) -> (tm_year,tm_isdst) 7.mktime(…) mktime(tuple) -> floating point number 8.strftime(…) strftime(format[,tuple]) -> string
print str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())) 2015-08-09 00:18:37 9.strptime(…) strptime(string,format) -> struct_time 10.time(…) time() -> floating point number 三、常用命令 1.python获取当前时间 time.time() 获取当前时间戳 print time.time() print time.localtime() print time.ctime() 结果为: 1439051479.08 time.struct_time(tm_year=2015,tm_mon=8,tm_mday=9,tm_hour=0,tm_min=31,tm_sec=19,tm_wday=6,tm_yday=221,tm_isdst=0) Sun Aug 9 00:31:19 2015 2.python格式化字符串 格式化成2009-03-20 11:45:39形式 time.strftime(“%Y-%m-%d %H:%M:%S”,time.localtime()) 格式化成Sat Mar 28 22:24:24 2009形式 time.strftime(“%a %b %d %H:%M:%S %Y”,time.localtime()) 3.将格式字符串转换为时间戳 a = “Sat Mar 28 22:24:24 2009″ b = time.mktime(time.strptime(a,”%a %b %d %H:%M:%S %Y”)) ps: 四、使用time模块计算代码执行效率的精度测试 #python中使用time模块计算代码执行效率 #测试用time.time()和time.clock()使用精度 import sys import time import timeit default_timer = None if sys.platform == "win32": # On Windows,the best timer is time.clock() default_timer = time.clock else: # On most other platforms the best timer is time.time() default_timer = time.time print default_timer timeIn= time.clock() for i in range(100): n=i timeUse = time.clock()-timeIn print timeUse timeIn = time.time() for i in range(100): n=i timeUse = time.time()-timeIn print timeUse timeIn = timeit.default_timer() for i in range(100): n=i timeUse = timeit.default_timer()-timeIn print timeUse #该段代码在windows下结果如下 >>> 4.07873067161e-005 0.0 3.5758734839e-005 #因为time.clock() 返回的是处理器时间,而因为 Unix 中 jiffy 的缘故,所以精度不会太高。 #因此,在Windows 系统中,建议使用 time.clock(),在Unix 系统中,建议使用 time.time(), #而使用timeit代替 time,就可以实现跨平台的精度性,使用timeit.default_timer()函数来获取时间 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |