自学Python的第七天,time库中的东西很多也很实用.
1. 时间获取
- time.time()表示从1970年0点0分到 目前经过的秒数
- time.ctime()表示通俗易懂的时间
- time.gmtime() 便于其他程序利用
2. 时间格式化
(1) strftime(tpl,ts)是时间格式化函数,其中tpl是格式化模板字符串,用来定义输出结果;ts是计算机内部时间类型变量,一般来说是time.gmtime().例如,
t=time.gmtime()
print(time.strftime("%Y-%B-%d %H:%M:%S",t))
输出的结果就是
其中格式化字符串有很多,列个表
格式化字符串 | 日期/时间说明 | 值范围和实例 |
---|---|---|
%Y | 年份 | 0000~9999,例如:1900 |
%m | 月份 | 01~12例如:10 |
%B | 月份名称 | Januaary~December,例如:April |
%b | 月份名称缩写 | Jane!Decoration,例如:April |
%d | 日期 | 0~31 |
%A | 星期 | Monday-Sunday |
%a | 星期缩写 | Mon-Sun |
%H | 小时(24) | 0-24 |
%I | 小时(12) | 0-12 |
%p | 上/下午 | AM/PM |
%M | 分钟 | 0-59 |
%S | 秒 | 0-59 |
(2) strptime(str,tpl)这个函数的作用是将一串字符串转换成计算机能够操作的一个时间. str是字符串形式的时间值 tpl是格式化模板字符串,用来定义输入效果,例如
timestr="2020-6-4 19:26:22"
print(time.strptime(timestr,"%Y-%m-%d %H:%M:%S"))
3.程序计时
(1)perf_counter() 该函数的作用是返回一个CPU级别的精确时间计数值,单位为秒,由于这个计数值起点不确定,所以最好是连续调用差值才有意义,例如
>>> start=time.perf_counter()
>>> finishi=time.perf_counter()
>>> finishi-start
18.2370292
(2)sleep(s) 休眠函数,s是休眠的时间,单位是秒,例如
>>> def wait():
time.sleep(3.3)
>>> wait()