时间戳
1: import time2: print(time.time())
可读的时间格式
1: import time2: print(time.ctime())3: later = time.time() + 6004: print(time.ctime(later))
结果
1: Wed Jan 30 17:11:49 20192: Wed Jan 30 17:21:49 2019
暂停程序(进程或者线程)
1: time.sleep(secs)
计时时钟
1: import time2: start = time.monotonic()3: time.sleep(0.1)
4: end = time.monotonic()5: print("start:", start)6: print("end:", end)7: print("span:", end - start)
结果
1: start: 18363.609
2: end: 18363.718
3: span: 0.10900000000037835
处理器时钟时间
反应的是程序运行实际使用的时间
1: time.clock()
组成时间格式
time模块定义struct_time来保存日期和时间值。
gmtime()函数以UTC格式返回当前时间。localtime应用当前时区的当前时间。mktime取一个实例转化为时间戳浮点数。
1: import time2: print(time.gmtime())3: print(time.gmtime().tm_mon)4: print(time.localtime())5: print(time.localtime().tm_yday)6: print(time.mktime(time.localtime()))
结果:
1: time.struct_time(tm_year=2019, tm_mon=1, tm_mday=30, tm_hour=9, tm_min=32, tm_sec=17, tm_wday=2, tm_yday=30, tm_isdst=0)
2: 13: time.struct_time(tm_year=2019, tm_mon=1, tm_mday=30, tm_hour=17, tm_min=32, tm_sec=17, tm_wday=2, tm_yday=30, tm_isdst=0)
4: 305: 1548840737.0
解析和格式化时间
函数strptime和strftime可以在时间值的struct_time表示和字符串表示之间转换。
1: import time2: now = time.ctime()
3: print("now:", now)4: parsed = time.strptime(now)
5: print("parsed time:", parsed)6: print(parsed.tm_year, parsed.tm_mon, parsed.tm_mday)
7: print("formatted time:", time.strftime("%a-%b-%d-%H:%M:%S %Y", parsed))
结果
1: now: Wed Jan 30 17:42:07 20192: parsed time: time.struct_time(tm_year=2019, tm_mon=1, tm_mday=30, tm_hour=17, tm_min=42, tm_sec=7, tm_wday=2, tm_yday=30, tm_isdst=-1)3: 2019 1 304: formatted time: Wed-Jan-30-17:42:07 2019