time库的使用

python的time库的功能

  • 计算机时间的表达
  • 提供获取系统时间并格式化输出功能
  • 提供系统级精确计时功能,用于程序性能分析

time库的相关函数

  • 时间获取:time(),ctime,gmtime()
  • 时间格式化:strftime(),strptime()
  • 程序计时:sleep(),perf_counter()

一、时间获取

1、time()
获取当前时间戳,即计算机内部时间只,是一个以秒为单位的浮点数。表示从1970年1月1日0:00开始到当前时刻的时间

import time    #导入time库
print(time.time())

运行结果:

1588050810.4218543

2、ctime()
获取当前时间,并以易读性方式表示,返回字符串

import time
print(time.ctime())

运行结果:

Tue Apr 28 13:15:57 2020

3、gmtime()
获取当前时间,返回一个time.struct_time的类,对于返回的类型,计算机可以对其直接进行处理

import time
print(time.gmtime())
print(type(time.gmtime()))

运行结果:

time.struct_time(tm_year=2020, tm_mon=4, tm_mday=28, tm_hour=5, tm_min=18, tm_sec=32, tm_wday=1, tm_yday=119, tm_isdst=0)
<class 'time.struct_time'>

二、时间格式化
时间格式化类似于字符串格式化,需要有展示模板,展示模板由特定的格式化控制符组成
常见的控制符如下

1、strftime(tql,ts)
tpl是格式化模板字符串,用来定义输出效果。ts是计算机内部时间类型变量

import time
t=time.gmtime()
now1=time.strftime("Now is %Y-%m-%d %H:%M:%S",t)
print(now1)
now2=time.strftime("现在是%Y年%m月%d日 %H时%M分%S秒",t)
print(now2)

运行结果:

Now is 2020-04-28 05:38:03
现在是2020年04月28日 05时38分03秒

2、strptime(str,tpl)
strptime()和strftime()互补,可以将字符串类型的时间数据读取.str是字符形式的时间值,tpl是格式化模板字符串,用来定义输入效果

import time
str="2020年4月28日13时42分10秒"
st=time.strptime(str,"%Y年%m月%d日%H时%M分%S秒")
str=time.strftime("%Y年%m月%d日 %H时%M分%S秒",st)
print(str)
2020年04月28日 13时42分10秒

三、程序计时
程序计时指测量起止动过所经历的时间过程

1、perf_counter()
返回一个CPU级别的精确时间计数值,单位为秒。由于这个数值的不确定性,连续调用差值才有意义

import time
start=time.perf_counter()
for i in range(10):
    print("hello world!")
end=time.perf_counter()
t=end-start
print(f'运行所需时间为{t}秒')
hello world!
hello world!
hello world!
hello world!
hello world!
hello world!
hello world!
hello world!
hello world!
hello world!
运行所需时间为0.03368020989000797秒

2、sleep(s)
s为指定的休眠时间,可以是浮点数

import time
start=time.perf_counter()
for i in range(10):
    print("hello world!")
    time.sleep(1)   #每打印一个"hello world"就休眠1秒
end=time.perf_counter()
t=end-start
print(f'运行所需时间为{t}秒')

运行结果:

hello world!
hello world!
hello world!
hello world!
hello world!
hello world!
hello world!
hello world!
hello world!
hello world!
运行所需时间为10.013963906094432秒
posted @ 2020-05-31 17:24  xjfyt  阅读(431)  评论(0编辑  收藏  举报